Skip to content

10.类型推断

一.赋值推断

赋值时推断,类型从右像左流动,会根据赋值推断出变量类型

let str = 'zhufeng';
let age = 11;
let boolean = true;
1
2
3

二.返回值推断

自动推断函数返回值类型

function sum(a: string, b: string) {
    return a + b;
}
sum('a','b');
1
2
3
4

三.函数推断

函数从左到右进行推断

type Sum = (a: string, b: string) => string;
const sum: Sum = (a, b) => a + b;
1
2

四.属性推断

可以通过属性值,推断出属性的类型

let person = {
    name:'zf',
    age:11
}
let {name,age} = person;
1
2
3
4
5

五.类型反推

可以使用typeof关键字反推变量类型

let person = {
    name:'zf',
    age:11
}
type Person = typeof person
1
2
3
4
5

六.索引访问操作符

interface IPerson {
    name:string,
    age:number,
    job:{
        address:string
    }
}
type job = IPerson['job']
1
2
3
4
5
6
7
8

七.类型映射

interface IPerson {
    name:string,
    age:number
}
type MapPerson = {[key in keyof IPerson]:IPerson[key]}
1
2
3
4
5

Released under the MIT License.