简体   繁体   中英

Typescript - optional types

How can I work with optional types in Typescript? For example I have an object called Conversation :

class Conversation {
    lastMessage?: Message
}

class Message {
    text: string
}

and I want to get nullable text from Message object through Conversation object.

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.

Release notes for 3.7 here .

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).

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). From the latest GitHub issue requesting optional changing :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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