Odpowiedzi:
Wszystkie pola w JavaScript (i w TypeScript) mogą mieć wartość nulllub undefined.
Możesz ustawić pole opcjonalne, które różni się od zerowalnego.
interface Employee1 {
name: string;
salary: number;
}
var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK
// OK
class SomeEmployeeA implements Employee1 {
public name = 'Bob';
public salary = 40000;
}
// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
public name: string;
}
Porównać z:
interface Employee2 {
name: string;
salary?: number;
}
var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number
// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
public name = 'Bob';
}
"strict" : false
salary:number|null;Jeśli to zrobisz, salary?:number; salary = null;pojawi się błąd. Jednak salary = undefined;w tym przypadku będzie działać dobrze. Rozwiązanie: użyj Unii, tj. „|”
Moim zdaniem typ Unii jest najlepszą opcją w tym przypadku:
interface Employee{
id: number;
name: string;
salary: number | null;
}
// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };
EDIT: Do tego, aby działać zgodnie z oczekiwaniami, należy włączyć strictNullChecksw tsconfig.
Aby być bardziej podobnym do C # , zdefiniuj Nullabletyp w ten sposób:
type Nullable<T> = T | null;
interface Employee{
id: number;
name: string;
salary: Nullable<number>;
}
Premia:
Aby Nullablezachować się jak wbudowany typ maszynopisu, zdefiniuj go w global.d.tspliku definicji w głównym folderze źródłowym. Ta ścieżka działała dla mnie:/src/global.d.ts
emp: Partial<Employee>, możemy zrobić emp.idlub emp.nameetc, ale jeśli mamy emp: Nullable<Employee>, nie możemy zrobićemp.id
Wystarczy dodać znak zapytania ?w polu opcjonalnym.
interface Employee{
id: number;
name: string;
salary?: number;
}
Możesz po prostu zaimplementować typ zdefiniowany przez użytkownika, taki jak poniżej:
type Nullable<T> = T | undefined | null;
var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok
var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok
// Type 'number[]' is not assignable to type 'string[]'.
// Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,2];
miałem to samo pytanie jakiś czas temu… wszystkie typy w ts są zerowalne, ponieważ void jest podtypem wszystkich typów (w przeciwieństwie do, na przykład, scala).
sprawdź, czy ten schemat blokowy pomaga - https://github.com/bcherny/language-types-comparison#typescript
voidbycie „podtypem wszystkich typów” ( typ dolny ), zapoznaj się z tym wątkiem . Również wykres, który podałeś dla Scali, jest również niepoprawny. Nothingw scala jest w rzeczywistości typem dna. Typescript, atm, nie ma typu bottom, podczas gdy scala ma .
Typ zerowy może wywoływać błąd czasu wykonywania. Myślę więc, że dobrze jest użyć opcji kompilatora --strictNullChecksi zadeklarować number | nulljako typ. także w przypadku funkcji zagnieżdżonej, chociaż typ danych wejściowych ma wartość NULL, kompilator nie może wiedzieć, co mogłoby się zepsuć, dlatego zalecam użycie !(wykrzyknik).
function broken(name: string | null): string {
function postfix(epithet: string) {
return name.charAt(0) + '. the ' + epithet; // error, 'name' is possibly null
}
name = name || "Bob";
return postfix("great");
}
function fixed(name: string | null): string {
function postfix(epithet: string) {
return name!.charAt(0) + '. the ' + epithet; // ok
}
name = name || "Bob";
return postfix("great");
}
Odniesienie. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions
typescript@nextteraz.)