3. TS 中函数类型

42 阅读1分钟
// type 定义一个函数类型
type Isum = (a: string, b: string) => string;
let sum: Isum = (a: string, b: string) => a + b; 
// void 表示不关心返回的具体类型
type Isum = (a: string, b: string) => void;
let sum: Isum = (a: string) => a;
- 函数可选参数
可选参数意味着可以不传,和 string | underfined 不同,string | underfined 是必须要传
function fun(a:string,b?:number){}
fun('abc')

function fun(a:string,b:number | undefined){}
fun('abc') // 参数 b 没赋值

- 可选参数只能在参数列表中的后面
function fun(a?:string,b:number){} // ts 报错:必需参数不能跟在可选参数后面。

let sum = (a: string = '123', b?: string): string => { // 第一个参数有默认值
    return a + b
}
sum('123')
sum('123',undefined)
sum('123','abc')
// 函数的剩余参数
let total = (...rest: number[]): number => {
    return rest.reduce((memo, current) => ((memo += current), memo))
}
// ts 中使用 typeof 来获取变量的类型
let num = 123
type N = typeof num // type N = number
let a:N = 123       // let a: number

// 获取对象的类型
let obj = {
    name: 'zhangsan',
    age: 18
}
type objType = typeof obj
// type objType = {
//     name: string;
//     age: number;
// }

// 获取类型的 key 值
type keyType = keyof typeof obj // "name" | "age"
// 获取对象的 value 的类型
type valueType = objType[keyType] // string | number