簡體   English   中英

Typescript 型號聲明區別

[英]Typescript type declaration difference

我是 Typescript 的新手,並試圖弄清楚以下 3 種類型之間的區別是什么:

field1?: string | null;
field2?: string;
field3:  string;

任何對 Typescript 文檔的參考以幫助我理解都會有所幫助。

interface A { field1?: string | null; }

在這里,您有一個可以省略(或undefined )的字段。 這用?:表示法表示。 如果定義了該字段,則它必須是stringnull

// The following are all allowed
const a1: A = { field1: 'abc' } // string
const a2: A = { field1: null } // null
const a3: A = {} // omitted
const a4: A = { field1: undefined } // explicit undefined

interface B { field2?: string; }

這意味着該字段可以省略或undefined 但如果它被定義,它必須是一個字符串。 這意味着不允許使用null

const b1: B = { field2: 'abc' } // string
const b2: B = { field2: null } // ERROR: field2 cannot be null
const b3: B = {} // omitted
const b4: B = { field2: undefined } // explicit undefined

interface C { field3: string; }

這意味着該字段必須是字符串。 它可能永遠不會被忽略。

const c1: C = { field3: 'abc' } // string
const c2: C = { field3: null } // ERROR: field3 cannot be null
const c3: C = {} // ERROR: field3 cannot be omitted
const c4: C = { field3: undefined } // ERROR: field3 cannot be undefined

操場


同樣相關的是,關於 null 和 undefined 之間的區別的問題:JavaScript 中的nullundefined 有什么區別?

你可以自己google一下。 可選屬性/參數。 在您的示例中:

field1?: string | null;

字符串類型的可選屬性 field1 或 null。 可選表示不需要且當前未定義。 這沒有錯誤。

field2?: string;

僅字符串類型的可選屬性 field2

field3:  string;

聲明了字符串類型的屬性,但實際上現在它沒有定義,這是錯誤的,並且必須在 class 構造函數中實現 field3。

暫無
暫無

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

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