Risposte:
Tutti i campi in JavaScript (e in TypeScript) possono avere il valore null
o undefined
.
È possibile rendere facoltativo il campo diverso da nullable.
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;
}
Confrontare con:
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;
Se lo fai salary?:number; salary = null;
Riceverai un errore. Tuttavia, salary = undefined;
funzionerà bene in questo caso. Soluzione: utilizzare Union, ovvero "|"
Il tipo di unione è nella mia mente l'opzione migliore in questo caso:
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: affinché questo funzioni come previsto, è necessario abilitare strictNullChecks
in tsconfig
.
Per essere più simile a C # , definisci il Nullable
tipo in questo modo:
type Nullable<T> = T | null;
interface Employee{
id: number;
name: string;
salary: Nullable<number>;
}
Bonus:
Per Nullable
comportarsi come un tipo Typescript incorporato, definirlo in un global.d.ts
file di definizione nella cartella di origine principale. Questo percorso ha funzionato per me:/src/global.d.ts
emp: Partial<Employee>
, possiamo fare emp.id
o emp.name
ecc, ma se abbiamo emp: Nullable<Employee>
, non possiamo farloemp.id
Aggiungi un punto interrogativo ?
al campo opzionale.
interface Employee{
id: number;
name: string;
salary?: number;
}
Puoi semplicemente implementare un tipo definito dall'utente come il seguente:
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];
ho avuto la stessa domanda qualche tempo fa .. tutti i tipi in ts sono nullable, perché void è un sottotipo di tutti i tipi (a differenza, ad esempio, di scala).
vedere se questo diagramma di flusso aiuta - https://github.com/bcherny/language-types-comparison#typescript
void
essere "sottotipo di tutti i tipi" ( tipo inferiore ), fare riferimento a questa discussione . Anche il grafico fornito per scala non è corretto. Nothing
in scala è, infatti, il tipo di fondo. Typescript, atm, non ha un tipo bottom mentre Scala lo ha .
Il tipo nullable può invocare un errore di runtime. Quindi penso che sia buono usare un'opzione del compilatore --strictNullChecks
e dichiarare number | null
come tipo. anche in caso di funzione annidata, sebbene il tipo di input sia nullo, il compilatore non può sapere che cosa potrebbe rompersi, quindi consiglio l'uso !
(punto esclamativo).
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");
}
Riferimento. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions
typescript@next
ora.)