Reputation: 30785
Why TS throws an error for this code? I have defined an interface Args
with length
property but it still throws:
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);
~~~~~~
Upvotes: 0
Views: 3368
Reputation: 249466
With <Args>
you are defining a generic type parameter (one that could be any type). 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;
}
Upvotes: 8