关于指定泛型的问题
来源:4-6 函数泛型

哈士奇附体
2020-06-14
/* 泛型generic 泛指的类型 */
type numberType = {
count: number
};
type stringType = string;
function a<T, P>(first: T, second: P) {
return `${first}${second}`
}
a<numberType, stringType>({count:123}, '3521')
老师我这里的a函数里面的first参数为什么没有提醒这个count属性呢,如果硬写上去那么会报错
any 类型
“T”上不存在属性“count”
直接在命令行执行的话会显示 Property ‘count’ does not exist on type ‘T’.
写回答
2回答
-
阿聪M
2021-07-21
/* 泛型generic 泛指的类型 */ class numberType {count: number = 0}; type stringType = string; function a<T, P>(first: T, second: P) { if (first instanceof numberType) { return `${first.count}${second}` } return `${first}${second}` } const b = { count: 123 } a<numberType, stringType>({ count: 123 }, '3521')
你应该是想在a函数中使用first.count,
然后这种情况就用上类型保护?
00 -
Dell
2020-06-20
不要用 {} ,请使用interface
022020-06-25
相似问题