13

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.

1

2 Answers 2

9

Starting from TypeScript 3.7 optional chaining is available.

Release notes for 3.7 here.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

4 Comments

I dont feel like this really answers the question, which was about typescript not javascript. Of course ts is transpiled to js, but they are still different things.
@robertotomás This is the official reason for the lack of support, TS tries not to add too much to JS syntax, and when it comes to expression level syntax they generally only add what is in JS or soon will be (ie is proposed and at stage 3), I will add a reference from GitHub shortly
@robertotomás added an official reference as to why the lack of JS support is an issue for TS in this case. Hope it makes things clear, let me know what you think.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.