- Mastering TypeScript 3
- Nathan Rozentals
- 247字
- 2021-07-02 12:42:47
Type aliases
Sometimes, when using union types, it can be difficult to remember what types are allowed. To cater for this, TypeScript introduces the concept of a type alias, where we can create a special named type for a type union. A type alias is, therefore, a convenient naming convention for union types. Type aliases can be used wherever normal types are used, and are denoted by using the type keyword. We can, therefore, simplify the use of union types in our code as follows:
type StringOrNumber = string | number; function addWithAlias( arg1 : StringOrNumber, arg2 : StringOrNumber ) { return arg1.toString() + arg2.toString(); }
Here, we have defined a type alias, named StringOrNumber, which is a union type that can be either a string or a number. We are then using this type alias in our function signature to allow both arg1 and arg2 to be either a string or a number.
Interestingly, type aliases can also be used for function signatures, as follows:
type CallbackWithString = (string) => void; function usingCallbackWithString( callback: CallbackWithString) { callback("this is a string"); }
Here, we have defined a type alias, named CallbackWithString, which is a function that takes a single string parameter and returns a void. Our usingCallbackWithString function accepts this type alias (which is a function signature) as its callback argument type.
When we need to use union types frequently within our code, type aliases provide an easier and more intuitive way of declaring named union types.