We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用索引类型,编译器可以检查使用动态属性名的代码。
keyof
T
keyof T
interface Person { name: string; age: number; } let personProps:keyof Person //personProps:"name" | "age"
T[K]
interface Person { name: string; age: number; } function demo<T extends object, K extends keyof T>(obj: T, names: K[]): T[K][] { return names.map(item => obj[item]) } let people: Person = { name: "test", age: 21 } let res1 = demo(people, ["name"]) //string[] 类型 let res2 = demo(people, ["name",'age']) //(string|number)[] 类型
T[K] 表明people['name']的类型为Person['name']。
类型别名和接口用法相似,但是还是有细微区别
interface Bird { fly(); layEggs(); } interface Fish { swim(); layEggs(); } // 有一个变量是Bird或者Fish中的一个,如何区分? function isFish(pet:Fish|Bird):pet is Fish{ return (<Fish>pet).swim!==undefined }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
索引类型( keyof & T[K ])
使用索引类型,编译器可以检查使用动态属性名的代码。
keyof
。对任何类型T
,keyof T
为已知类型T
的属性名的联合,比如T[K]
T[K]
表明people['name']的类型为Person['name']。接口(interface) 和 类型别名(type)的区别
类型别名和接口用法相似,但是还是有细微区别
类型区分&类型保护
用户自定义的类型保护
The text was updated successfully, but these errors were encountered: