1. Type inference
- TypeScript will infer a type when there is no explicit specified type, which is type inference
- If no variable is declared, no type is defined, and no value is assigned, then TS will infer that any type can perform any operation
let str
str = 456
str = null
Two, type alias
type关键字
(You can define a name for a type) It is mostly used for composite types
1. Define a type alias
/* 定义类型别名 */
type str = string
let s:str = '我是小青'
console.log(s);
2. Define a function alias
/* 定义函数别名 */
type str = () => string
let s: str = () => '我是小青'
console.log(s);
3. Define union type aliases
/* 定义联合类型别名 */
type str = string | number
let s1:str = 123
let s2: str = '123'
console.log(s1, s2);
4. Define an alias for the value
// 定义值的别名
type value = boolean | 0 | '213'
//变量s的值 只能是上面value定义的值
let s:value = true
console.log(s);
5. The difference between types and interfaces
- Interface uses extends inheritance, type uses & inheritance.
type s = number [] & B
interface A extends B {
}
interface B {
}
- Type can declare joint types and tuple types, but interface cannot
type s = number[] | B
interface A extends B {
name: string | number
}
interface B {
}
- Interface can implement declaration merging, but type cannot
interface test {
name: string
}
interface test {
age: number
}
/*
test实际为 {
name: string
age: number
}
*/
6. Advanced usage of type
- extends means inclusion, the value on the left will be a subtype of the type on the right
type a1 = 1 extends number ? 1 : 0 //1
type a2 = 1 extends Number ? 1 : 0 //1
type a3 = 1 extends Object ? 1 : 0 //1
type a4 = 1 extends any ? 1 : 0 //1
type a5 = 1 extends unknown ? 1 : 0 //1
type a6 = 1 extends never ? 1 : 0 //0
Three, never type
1. The use of never
- TypeScript will use the never type to represent state that should not exist
type A = '唱' | '跳' | 'rap'
function kun (value:A){
switch(value){
case '唱': break
case '跳': break
case 'rap': break
default:
// 兜底逻辑
const error: never =value;
break
}
}
2. The difference between never and void
- The void type just has no return value, but it will not make an error; nerve will only throw an exception and have no return value
//void类型只是没有返回值 但本身不会出错
function Void(): void {
console.log();
}
//只会抛出异常没有返回值
function Never(): never {
throw new Error('aaa')
}
- When we move the mouse up, we will find that there are only void and number. never will be removed directly in the union type