簡體   English   中英

如何在 TypeScript 中將類型聲明為可為空?

[英]How to declare a type as nullable in TypeScript?

我在TypeScript有一個接口。

interface Employee{
    id: number;
    name: string;
    salary: number;
}

我想將salary設為可為空的字段(就像我們在 C# 中所做的那樣)。 這可以在 TypeScript 中完成嗎?

JavaScript(和 TypeScript)中的所有字段都可以具有值nullundefined

您可以將字段設為可選,這與可為空不同。

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;
}

比較:

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';
}

在這種情況下,聯合類型是我認為的最佳選擇:

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 };

編輯:為了按預期工作,您應該在strictNullChecks中啟用tsconfig

為了更像C#,像這樣定義Nullable類型:

type Nullable<T> = T | null;

interface Employee{
   id: number;
   name: string;
   salary: Nullable<number>;
}

獎金:

要使Nullable表現得像內置的 Typescript 類型,請在根源文件夾中的global.d.ts定義文件中定義它。 這條路徑對我/src/global.d.ts/src/global.d.ts

就加個問號? 到可選字段。

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

你可以只實現一個用戶定義的類型,如下所示:

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];
type MyProps = {
  workoutType: string | null;
};

可空類型可以調用運行時錯誤。 所以我認為最好使用編譯器選項--strictNullChecks並聲明number | null number | null作為類型。 同樣在嵌套函數的情況下,雖然輸入類型為空,但編譯器不知道它會破壞什么,所以我建議使用! (感嘆號)。

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");
}

參考。 https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions

我通過編輯 tsconfig.json 文件解決了這個問題。

在: "strict": true下,添加這兩行:

"noImplicitAny": false,
"strictNullChecks": false,
type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};

然后你可以使用它

Nullable<Employee>

這樣您仍然可以使用Employee接口,因為它在其他地方

不久前我遇到了同樣的問題.. ts 中的所有類型都可以為空,因為 void 是所有類型的子類型(與例如 scala 不同)。

看看這個流程圖是否有幫助 -https://github.com/bcherny/language-types-comparison#typescript

type WithNullableFields<T, Fields> = {
  [K in keyof T]: K extends Fields 
    ? T[K] | null | undefined
    : T[K]
}

let employeeWithNullableSalary: WithNullableFields<Employee, "salary"> = {
  id: 1,
  name: "John",
  salary: null
}

或者您可以關閉 strictNullChecks;)

而相反的版本:

type WithNonNullableFields<T, Fields> = {
  [K in keyof T]: K extends Fields
    ? NonNullable<T[K]>
    : T[K]
}

把你的號碼的價值定義為未定義

var user: Employee = { name: null, salary: undefined }; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM