打字稿类型声明差异

时间:2020-07-20 19:33:53

标签: typescript

我是Typescript的新手,试图弄清楚以下三种类型之间的区别是什么:

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

任何有助于我理解的Typescript文档参考都会有用。

2 个答案:

答案 0 :(得分:1)

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

Playground


与此相关的还有一个关于nullundefined之间的区别的问题:What is the difference between null and undefined in JavaScript?

答案 1 :(得分:0)

您可以自己使用Google进行搜索。可选属性/参数。 在您的示例中:

field1?: string | null;

字符串或空类型的可选属性field1。可选方式是不需要的,当前未定义。没错。

field2?: string;

仅字符串类型的可选属性field2

field3:  string;

声明为字符串类型的属性,但是实际上它现在是未定义的,这是错误的,并且必须在类构造函数中实现field3。