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.
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.
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!
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With