打字稿通用与联合

时间:2019-06-11 08:48:17

标签: typescript

如果我使用value: string | number之类的参数定义函数类型,则可以定义该类型的函数(值:字符串)=> null。而且打字稿不显示任何警告。

但是,如果我使用通用参数<T extends string | number>(value: T)定义函数类型,则打字稿将显示错误。

有人可以解释这种行为吗?

代码示例

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 个答案:

答案 0 :(得分:0)

对于通用示例,您的表示法略有偏离:

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

Union示例将引发实际的编译器错误(如@zerkms所述),因为handleChange仅接受string,与string | number不兼容。