打字稿中的可选属性类 [英] Optional property class in typescript

查看:68
本文介绍了打字稿中的可选属性类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是打字稿的新手,我想知道打字稿中可选属性类的效用是什么?还有什么区别:

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;

推荐答案

可选属性:在 Typescript 中,您可以在界面中声明一个可选的属性.假设您有一个员工界面并且中间名是可选的,那么您的代码将如下所示:

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:

interface IEmployee {
  firstName: string;
  lastName: string;
  middleName?: string;
}

当有人使用你的接口 IEmployee 时,中间名将是可选的,但名字和姓氏是强制性的.

When someone will use your interface IEmployee then middleName will be optional but firstName and lastName is compulsory.

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.

希望能帮到你

这篇关于打字稿中的可选属性类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆