Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - optional types

Tags:

typescript

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.

like image 684
JaSHin Avatar asked May 07 '18 10:05

JaSHin


People also ask

What is optional TypeScript?

In Typescript, “?” represents optional parameters. We use optional parameters when it's not mandatory for that parameter to have a value or to be specified. Even if a function specifies parameters, you can call it without giving any arguments in JavaScript.

How do I specify optional properties in TypeScript?

First, if you don't tell TypeScript that a property is optional, it will expect it to be set. Adding ? to the property name on a type, interface, or class definition will mark that property as optional. type Foo = { bar?: number; } const a: Foo = {}; // This is now OK!

What does () => void mean TypeScript?

The syntax (a: string) => void means “a function with one parameter, named a , of type string, that doesn't have a return value”. Just like with function declarations, if a parameter type isn't specified, it's implicitly any .


2 Answers

Starting from TypeScript 3.7 optional chaining is available.

Release notes for 3.7 here.

like image 169
Radu Diță Avatar answered Sep 30 '22 06:09

Radu Diță


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.

like image 38
Titian Cernicova-Dragomir Avatar answered Sep 30 '22 06:09

Titian Cernicova-Dragomir