typescript 打字稿中的可选属性类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47942141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Optional property class in typescript
提问by asv
I'm new in typescript and I want to know what is the utility of optional property class in typescript? And what is the difference between:
我是打字稿的新手,我想知道打字稿中可选属性类的效用是什么?之间有什么区别:
a?: number;
a: number | undefined;
回答by Sandip Jaiswal
Optional property: In Typescript you can declare a property in your interface which will be optional. Suppose you have a interface for employee and middle name is optional then your code will look like this:
可选属性:在 Typescript 中,您可以在界面中声明一个可选属性。假设您有一个员工界面并且中间名是可选的,那么您的代码将如下所示:
interface IEmployee {
firstName: string;
lastName: string;
middleName?: string;
}
When someone will use your interface IEmployee then middleName will be optional but firstName and lastName is compulsory.
当有人使用您的接口 IEmployee 时, middleName 将是可选的,但 firstName 和 lastName 是强制性的。
let emp: IEmployee = { firstName: "Hohn", lastName: "Doe" }
Pipe Operator: Sometimes you want that a variable can hold multiple type. If you declared a property as number then it can hold only number. Pipe operator can tell typescript that it can hold multiple type. Other case where pipe operator is very useful when you return something from function and can return multiple type depend on condition.
管道运算符:有时您希望一个变量可以容纳多种类型。如果您将属性声明为数字,则它只能保存数字。管道运算符可以告诉打字稿它可以容纳多种类型。当您从函数返回某些内容并且可以根据条件返回多种类型时,管道运算符非常有用的其他情况。
Hope it will help
希望它会有所帮助
回答by Fenton
Parameters
参数
The difference between an optional parameter, and a parameter type number | undefined
is that you don't have to supply an argument...
可选参数和参数类型之间的区别在于number | undefined
您不必提供参数...
function a(a?: number) {
return a;
}
function b(a: number | undefined) {
return a;
}
// Okay
a();
b(1);
// Not okay: Expected 1 arguments, but got 0.
b();
This applies to functions, methods, and constructors.
这适用于函数、方法和构造函数。
Strict Null Checks
严格的空检查
If you switch on strict null checks, you'll find that any optional parameter, or property, will get a union type automatically. That means id
in the below example has the type number | undefined
, even though you only specified number
:
如果您打开严格的空检查,您会发现任何可选参数或属性都会自动获得联合类型。这意味着id
在下面的示例中具有 type number | undefined
,即使您只指定了number
:
// With strict null checks, this:
class Example {
id?: number;
}
// ... is the same as this:
class Example {
id?: number | undefined;
}
// ... and this:
class Example {
id: number | undefined;
}
I would recommend using the first example as it keeps your syntax consistent between properties and parameters.
我建议使用第一个示例,因为它可以使属性和参数之间的语法保持一致。