泛型
函数中的泛型
const join = <T, P>(first: T, second: P) => {
return `${first}${second}`
}
join<string, number>('1', 2)
function myFun<T>(params: Array<T>) {
return params
}
myFun<string>(['1', '2', '3'])
类中使用泛型
class Person<T extends number | string> {
constructor(private per: T[]) { }
choosePerson(index: number): T {
return this.per[index]
}
}
const ren = new Person(['牛恒', '浩哥', '巨哥', 23])
console.log('ren', ren.choosePerson(1));
interface RenA {
names: string,
age: number
}
class Person<T extends RenA> {
constructor(private per: T[]) { }
choosePerson(index: number): string {
return this.per[index].names
}
}
const ren = new Person([
{ names: '牛恒', age: 23 },
{ names: '浩哥', age: 26 },
{ names: '巨哥', age: 25 },
])
console.log('ren', ren.choosePerson(1));
interface AAA {
length: number
}
function fn<T extends AAA>(a: T): number {
return a.length
}
泛型接口
interface Generic<T> {
num: T,
config?: string
}
interface Props extends Generic<menuType> { }
as类型断言
interface iconType {
[propsname: string]: JSX.Element
}
const iconList = {
'/home': <UserOutlined />,
'/user-manage': <UserOutlined />,
'/user-manage/list': <UserOutlined />
} as iconType