Respostas:
Todos os campos em JavaScript (e em TypeScript) podem ter o valor nullou undefined.
Você pode tornar o campo opcional, diferente de nulo.
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;
}
Compare com:
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 você o fizer salary?:number; salary = null;, receberá um erro. No entanto, salary = undefined;funcionará bem neste caso. Solução: use Union, ou seja, '|'
O tipo de união é, na minha opinião, a melhor opção neste 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: Para que isso funcione conforme o esperado, você deve habilitar o strictNullChecksin tsconfig.
Para ser mais parecido com C # , defina o Nullabletipo assim:
type Nullable<T> = T | null;
interface Employee{
id: number;
name: string;
salary: Nullable<number>;
}
Bônus:
Para se Nullablecomportar como um tipo de TypeScript interno, defina-o em um global.d.tsarquivo de definição na pasta de origem raiz. Esse caminho funcionou para mim:/src/global.d.ts
emp: Partial<Employee>, podemos fazer emp.idou emp.nameetc, mas se tivermos emp: Nullable<Employee>, não podemos fazeremp.id
Basta adicionar um ponto de interrogação ?ao campo opcional.
interface Employee{
id: number;
name: string;
salary?: number;
}
Você pode apenas implementar um tipo definido pelo usuário, como o seguinte:
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];
Eu tive essa mesma pergunta há algum tempo .. todos os tipos em ts são anuláveis, porque void é um subtipo de todos os tipos (diferente de, por exemplo, scala).
veja se este fluxograma ajuda - https://github.com/bcherny/language-types-comparison#typescript
voidser 'subtipo de todos os tipos' ( tipo inferior ), consulte este tópico . Além disso, o gráfico que você forneceu para o scala também está incorreto. Nothingem scala é, de fato, o tipo inferior. Datilografado, atm, não têm tipo de fundo, enquanto scala faz .
O tipo anulável pode chamar um erro de tempo de execução. Então, acho bom usar uma opção de compilador --strictNullCheckse declarar number | nullcomo tipo. também no caso de função aninhada, embora o tipo de entrada seja nulo, o compilador não pode saber o que poderia quebrar, por isso recomendo o uso !(ponto de exclamação).
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");
}
Referência. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions
typescript@nextagora).