简体   繁体   English

Typescript 型号声明区别

[英]Typescript type declaration difference

I'm new to Typescript and trying to figure out what the difference between the following 3 types is:我是 Typescript 的新手,并试图弄清楚以下 3 种类型之间的区别是什么:

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

Any reference to Typescript docs to help me understand would be helpful.任何对 Typescript 文档的参考以帮助我理解都会有所帮助。

interface A { field1?: string | null; }

Here you have a field that can be omitted (or undefined ).在这里,您有一个可以省略(或undefined )的字段。 That is denoted with the ?: notation.这用?:表示法表示。 And if the field is defined, it must be either, string or null .如果定义了该字段,则它必须是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; }

This means the field may be omitted or undefined .这意味着该字段可以省略或undefined But if it is defined it must be a string.但如果它被定义,它必须是一个字符串。 This means null is not allowed.这意味着不允许使用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; }

This means the field must be a string.这意味着该字段必须是字符串。 It may never be omitted.它可能永远不会被忽略。

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 操场


Also relevant, a question about the different between null and undefined : What is the difference between null and undefined in JavaScript?同样相关的是,关于 null 和 undefined 之间的区别的问题:JavaScript 中的nullundefined 有什么区别?

You can google it by youself.你可以自己google一下。 Optional property/parameter.可选属性/参数。 In your example:在您的示例中:

field1?: string | null;

optional property field1 of type string or null.字符串类型的可选属性 field1 或 null。 Optional means not required and currently undefined.可选表示不需要且当前未定义。 That's no error.这没有错误。

field2?: string;

optional property field2 of type only string仅字符串类型的可选属性 field2

field3:  string;

declared property of type string, but actually now it has undefined, that's error, and field3 has to be implemented in class constructor.声明了字符串类型的属性,但实际上现在它没有定义,这是错误的,并且必须在 class 构造函数中实现 field3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM