【发布时间】:2021-04-19 04:01:35
【问题描述】:
我有一个问题归结为尝试将具有特定参数类型的函数分配给期望具有泛型类型的函数的变量:
const s: <T>(v: T)=>string
= (v: string[])=>(v[0]||'x');
Typescript 给出以下错误:
类型 '(v: string[]) => string' 不可分配给类型 '(v: T) => string'。参数“v”和“v”的类型不兼容。类型 'T' 不能分配给类型 'string[]'。
这个错误对我来说没有多大意义,因为似乎string[] 是用于通用T 的完全合理的类型。
有一个相关问题具有相同的潜在问题,但答案是针对该问题的具体情况:Why is this TypeScript class implementing the interface not assignable to a generic constraint extending the interface?
【问题讨论】:
-
<T>(v: T) => string表示可以消费任何东西并输出字符串的函数类型;你的函数只能使用一个字符串数组。 -
const s: <T extends string[]>(v: T) => string = (v: string[]) => (v[0] || 'x');
标签: typescript typescript-generics