Sunday, November 17, 2024
I found a few additional differences in the TypeScript documentation that are not mentioned in the Swift-TypeScript cheatsheet I linked in one of my previous posts:
- The return type of a function can be inferred. If there’s no return type specified in the declaration, it doesn’t mean the function returns
void
. - Optionality in TypeScript is implemented at the property level, not in the type system. To make a property optional, add ? at the end of the property name. There are utility types in TypeScript that can change the optionality of properties, such as
Partial<Type>
andRequired<Type>
. - Use
extends
keyword to add type constraints in generics:<T1, T2 extends T1>
- Use
&
to “combine” two or more types into one. It will create a new type that contains properties from all combined types. - Use
|
to create aunion
type that can be one of the types being “united”. - To make illegal states unrepresentable Swift devs often use enums with associated types. To mimic Swift’s
switch
onenum
with associated types use union of interfaces representing associated types and add a tag with unique literal types to each interface. Then, useswitch
on the tag of union type, that’s enough to guarantee type safety. - For
RawRepresentable
enums it’s usually more efficient to use a union of literal types representing values because it doesn’t add extra run-time code like TS’senum
. Another alternative isconst enum
, but there is something in the TS documentation about potential problems with it. keyof
is a way to provide a type for dynamic member lookups. It’s somewhat similar tokeypath
in Swift.typeof
, when used inside conditions, allows for narrowing the type in a conditional branch.- “Indexed access type” allows to get type of a property by using indexed access syntax:
type ContactID = Contact["id"]
- Tuple in TS is a sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions. Example:
type StringNumberPair = [string, number];
describes array whose 0 index contains a string and whose 1 index contains a number. - Resources cleanup in Swift’s
deinit
can be mimicked by adding[Symbol.dispose]()
method to a class and then storing created instance withusing
keyword instead of const or let.