1. The Number type
let count: number = 10
// ES5: var count = 10;
Copy the code
2. Type String
let name: string = 'hello world'
// ES5: var name = 'hello world';
Copy the code
3. The Boolean type
let isCheck: boolean = false
// ES5: var isCheck = false;
Copy the code
4. The Symbol type
const sym = Symbol(a)let obj = {
[sym]: 'hello world',}console.log(obj[sym]) // hello world
Copy the code
5. Null and Undefined
In TypeScript, undefined and NULL have their own types: undefined and NULL.
let u: undefined = undefined
let n: null = null
Copy the code
6. An Array type
In TypeScript, array types can be expressed in two ways:
- Direct expression:
type[]
. - In generic form:
Array<type>
.
let array: number[] = [1.2.3]
// ES5: var array = [1,2,3];
let array: Array<number> = [1.2.3] // Array
generic syntax
// ES5: var array = [1,2,3];
Copy the code
7. Tuple type
Arrays combine values of the same type, while tuples combine values of different types
let array: number[] = [100.200]
let tuple: [number.string] = [100.'200']
Copy the code
When assigning or accessing an element with a known index, the correct type is obtained:
let tuple: [string.number]
tuple[0] = 'Jack'
tuple[1] = 22
tuple[0].substr(1) //String unique method
tuple[1].toFixed(2) //Number unique method
Copy the code
Tuples are of fixed length and fixed type
let tuple: [string.number]
tuple = ['jack'] / / ❌
tuple = [100.'juck'] / / ❌
tuple = ['juck'.100] / / ✅
Copy the code
UseState in React returns the tuple type:
// Type definition: return tuple type [S, Dispatch
>]
function useState<S> (initialState: S | (() => S)) :S.Dispatch<SetStateAction<S>>] // Tuple: destruct assignmentconst [state.setState] = useState(0)
Copy the code
The difference between an Array and a Tuple
Array
Type unity,Tuple
The type can be different.Array
No limit in length,Tuple
Length limit.
8. Enum (Enum) Type
Using enumerations we can define named constants to express values that are limited to a certain range. TypeScript supports numeric and string-based enumerations.
1. Enumeration of numbers
enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH //let dir = 0
Copy the code
By default, NORTH starts at 0, and the remaining members automatically grow by +1. In other words, direction.south is valued at 1, direction.east is valued at 2, and direction.west is valued at 3.
We can also set the initial value of NORTH, such as:
enum Direction {
NORTH = 3,
SOUTH, / / 4
EAST, / / 5
WEST, / / 6
}
Copy the code
2. String enumeration
In TypeScript 2.4, we are allowed to use string enumerations. In a string enumeration, each member must be initialized with a string literal, or with another string enumeration member.
enum Direction {
NORTH = 'NORTH',
SOUTH = 'SOUTH',
EAST = 'EAST',
WEST = 'WEST',}let dir: Direction = Direction.NORTH //let dir = 'NORTH'
Copy the code
Instead of using enumerated types, I recommend using union types to express constraints on a set of values:
const Direction = 'NORTH' | 'SOUTH' | 'EAST' | 'WEST'
let dir: Direction = 'NORTH'
Copy the code
9. The Object type
Type Object: This is the type of all instances of class Object. It is defined by the following two interfaces:
Object
The interface is definedObject.prototype
A property on a prototype object;
// node_modules/typescript/lib/lib.es5.d.ts
interface Object {
constructor: Function
toString(): string
toLocaleString(): string
valueOf(): Object
hasOwnProperty(v: PropertyKey): boolean
isPrototypeOf(v: Object) :boolean
propertyIsEnumerable(v: PropertyKey): boolean
}
Copy the code
ObjectConstructor
The interface is definedObject
Class.
// node_modules/typescript/lib/lib.es5.d.ts
interface ObjectConstructor {
/** Invocation via `new` */
new(value? :any) :Object
/** Invocation via function calls */(value? :any) :any
readonly prototype: Object
getPrototypeOf(o: any) :any
/ /...
}
Copy the code
All instances of class Object inherit all properties from the Object interface.
10. Any type
In TypeScript, any type can be classified as any. This makes the any type the top-level type of the type system (also known as the global supertype).
let value: any = Awesome!
value = 'hello'
value = false
value = {}
value = []
Copy the code
The any type provides a smooth transition from JavaScript to TypeScript: You can assign any type to any and perform any operation on any values without static type checking of any kind.
let value: any
value.foo.bar / / ✅
value.trim() / / ✅
value() / / ✅
new value() / / ✅
value[0] [1] / / ✅
Copy the code
In many scenarios, this is too loose. Using the any type, you can easily write code that is of the right type but problematic at run time. If we use any, we won’t be able to use many of TypeScript’s protections. To address the problem of any, TypeScript 3.0 introduces unknown types.
11. Unknown type
Just as all types can be assigned to any, all types can be assigned to unknown.
let value: unknown = Awesome!
value = 'hello'
value = false
value = {}
value = []
Copy the code
But you cannot assign an unknown type to an already identified type: that is, the unknown type can only be assigned to any and the unknown type itself.
let value: unknown
let value1: unknown = value / / ✅
let value2: any = value / / ✅
let value3: boolean = value / / ❌
let value4: number = value / / ❌
let value5: string = value / / ❌
let value6: object = value / / ❌
let value7: any[] = value / / ❌
let value8: Function = value / / ❌
Copy the code
Also, unknown cannot perform any operations like any:
let value: unknown
value.foo.bar / / ❌
value.trim() / / ❌
value() / / ❌
new value() / / ❌
value[0] [1] / / ❌
Copy the code
What is the difference between any type and unknown type?
type | any | unknown |
---|---|---|
The assigned value | Can be assigned any value | Can be assigned any value |
The assignment | You can assign to any variable | Can only be assigned toany 和 unknown Type variable |
operation | You can do anything you want | All operations are forbidden |
12. The Void type
In some ways, the void type looks like the opposite of any. It means there is no type. When a function does not return a value, you will usually see a return value of type void:
function doSomething() :void {
console.log('do something')}Copy the code
Note that declaring a void variable is useless, since in strict mode it can only be undefined:
let unusable: void = undefined
Copy the code
13. Never type
The never type represents the type of values that will never exist. For example, the type never is the return value type for function or arrow function expressions that always throw an exception or never return a value at all.
// Function never returns
function error(message: string) :never {
throw new Error(message)
}
Copy the code
For example, the crossover type of the base type also returns never because there was never any intersection between them:
let value = '1' & 1 // never
Copy the code
In TypeScript, you can use the never feature to implement comprehensiveness checks. Here’s an example:
type Foo = string | number
function controlFlowAnalysisWithNever(foo: Foo) {
if (typeof foo === 'string') {
// Here foo is narrowed to string
} else if (typeof foo === 'number') {
// Here foo is narrowed to the number type
} else {
// Foo in this case is never
const check: never = foo
}
}
Copy the code
Notice that in the else branch, we assign foo, narrowed down to never, to a variable that displays the declaration of never. If all logic is correct, then this should compile through. But suppose one day your colleague changes the type of Foo:
type Foo = string | number | boolean
Copy the code
But he forgot to modify controlFlowAnalysisWithNever method in control process at the same time, this time the else branch foo type can be narrowed to a Boolean type, lead to cannot be assigned to never type, then will generate a compiler error. In this way, we can make sure controlFlowAnalysisWithNever method always end with all possible types of Foo. From this example, we can conclude that using never avoids the possibility that there is no corresponding implementation for a newly joined type, in order to write type-safe code.
reference
TypeScript Chinese manual
A rare TS study guide