Optional types syntax (2 defs: w/ type
and w/ inline definition)
#51926
Labels
Declined
The issue was declined as something which matches the TypeScript vision
Suggestion
An idea for TypeScript
This is not a duplicate request, as pointed out in this comment, so please elaborate before quickly marking this as a duplicate. It may look similar to other requests before, but I have not found any quite the same.
Suggestion
🔍 Search Terms
type optional syntax variable definition
✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
I think it could be very useful to be able to declare optional types in TypeScript in a more clear and consise way. This proposal is two-fold— one syntax for defining a
type
and one syntax for inline typing on a variable.type
usage, I propose a shorthand syntaxTypeName ?= Type
which would match for the specified type orundefined
, where the?=
indicates that it is optional and can match either the specified type orundefined
.let variableName ?: Type
which would type the variable as the specified type orundefined
, where the?:
indicates that the variable is optional and can either be of the specified type orundefined
.This syntax would provide a more concise and readable way to create optional variables, as opposed to using the
| undefined
syntax which can be somewhat unwieldy, especially when creating a handful of variables you want toi be optional within a framework.This would make it easier to clearly communicate the intended use of a variable to other developers reading your code.
📃 Motivating Example
You could use the optional
type
syntax to create an optionaltype
and then use it like this:You could use the optional inline variable syntax to create an optional
type
on the variable like this:…but what if someone uses both?
It's plausible that in some cases, a user may use the optional inline syntax using a type that already uses the optional
type
syntax, or create unions or intersections using some optional and other non-optional types.For union types, that could look something like this:
In these cases, I think it woulkd make the most the most sense just to let any types declared with the an optional declaration be shorthand for their same usage as
Type | undefined
, so in the above example, the type forpersonalDetail
would evaluate tostring | undefined | number
.For intersection types, the type would usually evaluate to
never
, the same that it would if union-ing withundefined
, like in this example:💻 Use Cases
Working within Svelte, for example, it's not uncommon to see TypeScript used like this when defining props:
With this proposal implemented, this block could be rewritten to the following:
The space here would be optional, as always, so this would produce the same result:
The text was updated successfully, but these errors were encountered: