patrickjtoy
patrickjtoy

Reputation: 15

Why does type inference break down when generic types are present?

For example, type inference works perfectly in the below snippet:

export type trim = (value: string) => string;
export const trim: trim = value => value.trim();

The compiler correctly identifies the argument "value" in the anonymous function as type "string" as expected. However, I've noticed that the same is not true when a generic type is introduced as in the below snippet:

export type identity = <T>(value: T) => T;
export const identity: identity = <T>(value: T) => value;

If I remove the type annotations from the function definition, the compiler assumes the argument "value" has a type of "any" when I expect it to resolve a type of "T". I'd like to be able to remove the type annotations from the function definition and write them above the function for code clarity. Is this possible to do when generics are present in TypeScript?

Upvotes: 0

Views: 83

Answers (1)

Paarth
Paarth

Reputation: 10377

It doesn't break down. You've typed the const identity as being of the identity type. NOT the lambda. The lambda you've created is, appropriately, any => any. Once you assign it, it becomes specialized to the type you're looking for.

However, the type information if you inspect the identity constant is in fact <T>(value: T) => T;

export type identity = <T>(value: T) => T;
export const identity: identity = (value) => value;

let test:string = identity(4)

When the compiler gets to the last line it fails with

error TS2322: Type 'number' is not assignable to type 'string'.

Upvotes: 1

Related Questions