简体   繁体   English

打字稿 - 可选类型

[英]Typescript - optional types

How can I work with optional types in Typescript?如何在 Typescript 中使用可选类型? For example I have an object called Conversation :例如,我有一个名为Conversation的对象:

class Conversation {
    lastMessage?: Message
}

class Message {
    text: string
}

and I want to get nullable text from Message object through Conversation object.我想通过Conversation对象从Message对象获取可为空的text

const lastMessageText?: string = conversation?.lastMessage.text

but this syntax doesn't work.但这种语法不起作用。 I can't write ?我不会写? after the conversation.谈话之后。

Starting from TypeScript 3.7 optional chaining is available.TypeScript 3.7开始, optional chaining可用。

Release notes for 3.7 here . 3.7发行说明在这里

There is a proposal to add the ?.有一个建议添加?. operator to JavaScript, but it is not sufficiently further along in the spec process to be implemented in Typescript yet (since Typescript want to remain a superset of JavaScript the team does not usually add proposed features until they are in the final stages).运算符到 JavaScript,但在规范过程中还不足以在 Typescript 中实现(因为 Typescript 希望保持 JavaScript 的超集,因此团队通常不会添加提议的功能,直到它们进入最后阶段)。

You can use the && operator to achieve a similar effect although more verbose:您可以使用&&运算符来实现类似的效果,但更冗长:

const conversation: Conversation = {

}
const lastMessageText = conversation.lastMessage && conversation.lastMessage.text // is of type string| undefined

EDIT编辑

Currently The optional chaining JS feature is not yet as stage 3, typescript will only support JS proposals that are at stage 3 when it comes to expression level syntax (when it comes to types they do their own thing).目前,可选链 JS 功能还没有达到第 3 阶段,typescript 将只支持在表达式级别语法方面处于第 3 阶段的 JS 提案(当涉及到类型时,他们做自己的事情)。 From the latest GitHub issue requesting optional changing :从要求可选更改的最新 GitHub 问题

After being burned multiple times by adding features to TS only to have the semantic rug pulled out from under us at the last second, there is seriously no number of upvotes that would have us adding a feature that could potentially drastically change runtime behavior at some point in the future.在通过向 TS 添加功能而被多次烧毁之后,在最后一秒才将语义地毯从我们下面拉出来,真的没有多少赞成票会让我们添加一个可能会在某些时候彻底改变运行时行为的功能在将来。

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

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