This article is the first in a series of TypeScript Tutorials.
In our last article, Primitive Types (I), we introduced primitive data types and several other new TypeScript primitive types. This article continues with the remaining basic types, including array, tuple, object, literal, and enum types.
[TOC]
An array type
TypeScript provides two ways to define array types. One is to add [] to the element type to indicate that it is an array. Another approach is to use a generic representation: Array
, where T is the type of the element in the Array.
For the moment, you can think of generics as parameters of types. For those of you who are not familiar with strongly typed languages, this might be a little difficult to understand.
/ / the first
let fruits: string[] = ['Apple'.'Banana'.'Orange']
/ / the second
let fruits: Array<string> = ['Apple'.'Banana'.'Orange']
Copy the code
In general, we prefer the first representation when the array elements are of simple type, as in the example above. The second way to use generics is to represent more complex types.
Such as:
/ / "|" is used to represent joint type, here said the elements in the array to a string or number type
let x: Array<string | number>
x = ['Hello'.'World'.42]
Copy the code
A tuple type
At first glance, tuples are similar to lists in that they are used to represent a set of data. The difference is that the length of tuples is finite, and the type of each element can be defined separately.
A common use is to save the result of a function’s execution.
let status: [string.number] = submit(data, urlPath)
console.log(status)
// => ['error', 400]
Copy the code
Object type
Object indicates a type other than the original type. That is, variables defined as object cannot be assigned to string, number, Boolean, symbol, NULL, or undefined. (For null and undefined, StrictNullChecks must be enabled.
The existence of the object type allows for stricter type definitions. For example, for the object.create () function, the library definition looks like this:
interface ObjectConstructor {
/** * Creates an object that has the specified prototype or that has null prototype. * @param o Object to use as a prototype. May be null. */
create(o: object | null) :any;
}
Copy the code
Object.create() creates a new Object using an existing Object or null. After the above definition, TypeScript will report an error at compile time when you accidentally pass in a raw value other than NULL.
Object.create({}) // OK
Object.create(null) // OK
Object.create('hello') // Error
Object.create(123) // Error
Object.create(true) // Error
Object.create(undefined) // Error
Copy the code
Literal type
Literal types allow you to constrain the possible values of a variable, including string literals, number literals, and Boolean literals. It is usually used with type aliases and union types.
Boolean literal type
let lovePeace: true
lovePeace = true // OK
lovePeace = false // Error
Copy the code
String literal type
Used to constrain the possible values of a string.
type Effect = 'ease-in' | 'ease-out' | 'ease-in-out'
function animate(ele: Element, effect: Effect) {
// ...
}
animate(document.getElementById('app'), 'ease-in')
animate(document.getElementById('app'), 'fade-in') // Error
Copy the code
Numeric literal type
For example, the result of a die roll can only be between 1 and 6.
function rollDice() : 1 | 2 | 3 | 4 5 | | 6{
// ...
}
Copy the code
Enumerated type
Enumerations are an organization’s way of collecting a set of related variables. In TypeScript, the enum keyword is defined. TS supports two types of enumeration: numeral-based enumeration and string-based enumeration.
Digital enumeration
First let’s look at enumerations based on numbers:
enum Color {
Red,
Green,
Blue
}
Copy the code
Above we define a numeric enumeration Color that has three members, Red, Green, and Blue. By default, the first member has a value of 0 and the remaining members are incremented.
Color.Red === 0
Color.Green === 1
Color.Blue === 2
Copy the code
You can also set the initial value of the enumerator, and the subsequent values will continue to increase.
enum Color {
Red = 1,
Green,
Blue
}
console.log(Color.Red, Color.Green, Color.Blue)
// => 1 2 3
Copy the code
When using numeric enumerations, TS generates a reverse mapping for the enumeration members. For example, for the example above:
Color.Red === 1
Color[1= = ='Red'
Copy the code
String enumeration
String enumerations allow you to initialize an enumerator using a string, either a string literal or another string enumerator.
enum Color {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE'
}
Copy the code
String enumeration members do not grow by themselves, and each member must be initialized. In addition, string enumerations do not generate reverse mappings for members.
With regard to TS enumerated types, the above content basically covers common cases. In addition, there are a lot of details, the space reasons, go here, interested can refer to [this article] (https://jkchao.github.io/typescript-book-chinese/typings/enums.html).
summary
This article focuses on the other basic types in TS: array, tuple, Object, literal, and enum types.