

So in our example above we were able to assign U extends Foo ? string : number to string | number since no matter what the conditional evaluates to, it’s known to be either string or number. In the meantime, we can assign a conditional type to any other target type as long as each branch of the conditional is assignable to that target. When another piece of code ends up calling foo, it will substitute in U with some other type, and TypeScript will re-evaluate the conditional type, deciding whether it can actually pick a branch. In the above, the variable a has a conditional type that hasn’t yet chosen a branch. Take a simple calculator that returns this after each operation:

This makes hierarchical fluent interfaces much easier to express, for example. This is called F-bounded polymorphism, a lot of people know it as the fluent API pattern. Polymorphic this typesĪ polymorphic this type represents a type that is the subtype of the containing class or interface. Much of the time when we talk about “singleton types”, we’re referring to both enum member types as well as numeric/string literal types, though many users will use “singleton types” and “literal types” interchangeably. Enum Member TypesĪs mentioned in our section on enums, enum members have types when every member is literal-initialized. On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go. InterfaceĪdding new fields to an existing interfaceĪ type cannot be changed after being createdīecause an interface more closely maps how JavaScript objects work by being open to extension, we recommend using an interface over a type alias when possible. Type AliasesĪs we mentioned, type aliases can act sort of like interfaces however, there are some subtle differences.Īlmost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable. (property) next: LinkedList Try Interfaces vs.
