[英]TypeScript generics error: Property does not exist on type
Why TS throws an error for this code? 为什么TS会为此代码引发错误? I have defined an interface Args
with length
property but it still throws: 我已经定义了一个带有length
属性的interface Args
,但是它仍然抛出:
interface Args {
length: number
}
function log<Args>(arg: Args): Args {
console.log(arg.length); // <= why length doesn't exist?
return arg;
}
$ tsc index.ts
index.ts:11:19 - error TS2339: Property 'length' does not exist on type 'Args'.
11 console.log(arg.length);
~~~~~~
With <Args>
you are defining a generic type parameter (one that could be any type). 使用<Args>
您可以定义一个通用类型参数(可以是任何类型的参数)。 You could define a type parameter with a constraint: 您可以使用约束定义类型参数:
interface Args {
length: number
}
function log<T extends Args>(arg: T): T {
console.log(arg.length);
return arg;
}
Or you could omit the type parameter altogether (depending on what you want to do) 或者,您可以完全忽略类型参数(取决于您要执行的操作)
interface Args {
length: number
}
function log(arg: Args): Args {
console.log(arg.length);
return arg;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.