Green
Green

Reputation: 30785

TypeScript generics error: Property does not exist on type

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

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions