JaSHin
JaSHin

Reputation: 277

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.

Upvotes: 13

Views: 40799

Answers (2)

Radu Diță
Radu Diță

Reputation: 14171

Starting from TypeScript 3.7 optional chaining is available.

Release notes for 3.7 here.

Upvotes: 9

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249606

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.

Upvotes: 4

Related Questions