①. 在TS中,数组、字符串、数组、接口非常常见
②. 如果要定义一个对象的key和value类型,可以用到TS的Record:
a. Record后面的泛型就是对象键和值的类型
③. Record<K, T>构造具有给定类型T的一组属性K的类型
(1). 之前写法:
const nav: any = {}
const nav: { [key: 'A' | 'B' | 'C'] : number } = {}
(2). 需要一个对象,有ABC三个属性,属性的值必须是数字:
// 示例1
type keys = 'A' | 'B' | 'C'
const result: Record<keys, number> = {
A: 1,
B: 2,
C: 3
}
// 示例2
interface PageInfo {
title: string;
}
type Page = "home" | "about" | "contact"
const nav: Record<Page, PageInfo> = {
about: { title: "about" },
contact: { title: "contact" },
home: { title: "home" },
}
①. Partial可以快速把某个接口类型中定义的属性变成可选的(Optional)
(1). Partial类型的定义:
// Make all properties in T optional
type Partial<T> = {
[P in keyof T]?: T[P];
}
// 定义user的接口
interface IUser {
name: string
age: number
department: string
}
// 经过Partial类型转化后得到
type optional = Partial<IUser>
// optional的结果:
type optional = {
name?: string | undefined;
age?: number | undefined;
department?: string | undefined;
}