- keyof T,索引类型操作符。对于任何类型T,keyof T的结果为T上已知的公共属性名的联合。
interface User {
name: string;
age: number;
work: string;
}
function test<T, Key extends keyof T> (obj: T, key: Key): T[Key] {
return obj[key];
}
test({
name: 'w',
age: 1,
work: 'w'
}, 'name');
- or
interface User {
name: string;
age: number;
work: string;
}
type UserKey = keyof User;
function test (obj: User, key: UserKey): User[UserKey] {
return obj[key];
}
test({
name: 'w',
age: 1,
work: 'w'
}, 'name')
网友评论