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> and Required<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 a union 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 on enum with associated types use union of interfaces representing associated types and add a tag with unique literal types to each interface. Then, use switch 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’s enum. Another alternative is const 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 to keypath 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.