0
votes

If i define function type with parameter like value: string | number, I can define function (value: string) => null of that type. And typescript don't show any warnings.

But if I define function type with generic parameter <T extends string | number>(value: T), then typescript will show error.

Could someone explain this behaviour?

code sample

type OnChangeUnion = (value: string | number) => void;

type OnChangeGeneric = <T extends string | number>(value: T) => void;

const handleChange = (value: string) => null;

const onChange: OnChangeGeneric = handleChange;
const onChangeA: OnChangeUnion = handleChange;

playground

1
Tbh if you enable all checks (see "Options" on the playground) you see that both assignments fail. - zerkms
They are both bad assignments... both OnChangeUnion and OnChangeGeneric are function types which must accept a string | number argument. But handleChange only accepts a string argument, so it is neither an OnChangeUnion nor an OnChangeGeneric. - jcalz

1 Answers

0
votes

For the Generic example, your notation is just slightly off:

type OnChangeGeneric<T extends string | number> = (value: T) => void;
const handleChange = (value: string) => null;
const onChange: OnChangeGeneric<string> = handleChange;

The Union example will throw an actual compiler error (as noted by @zerkms), as handleChange only accepts a string, which is not compatible with string | number.