9

Consider the following generic function in TypeScript:

interface Foo { id: string; }
const foo = <Foo>{id: 'bar'};
function baz<T>(x: T) { console.log(x.id); }
baz(foo);

This doesn't compile:

test.ts(6,17): error TS2339: Property 'id' does not exist on type 'T'.

It seems to me that TypeScript ought to be able to deal with this situation. If it can't, then I have to do something like this:

interface IHasId { id: string; }
interface Foo extends IHasId { }
const foo = <Foo>{id: 'bar'};
function baz<T>(x: IHasId) { console.log(x.id); }
baz<Foo>(foo);

Is there any alternative or more idiomatic way to deal with this situation?

1
  • Use any instead? Commented Jul 2, 2016 at 12:21

1 Answer 1

22

It makes sense, that first sample doesn't compile. Typescript is all about adding type checking.If you want to disable it you could use any, but why use generics in this case?

If you want to define constraint on generic type, you can do it this way:

function baz<T extends IHasId>(x: T) { console.log(x.id); }

By the way, constraint can be defined inline:

function baz<T extends { id: string; }>(x: T) { console.log(x.id); }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.