mer*_*ito 3 javascript type-systems duck-typing typescript
const s: string = 'foo';
const pass1 = (origin: string) => origin.concat(s);
const pass2 = (origin: string[]) => origin.concat(s);
type S = string | string[];
const error = (origin: S) => origin.concat(s);
Run Code Online (Sandbox Code Playgroud)
上面的代码。我可以调用concatastring或string[]type。那么,为什么打字稿禁止拨打concat的string | string[]类型?
错误是:
Cannot invoke an expression whose type lacks a call signature.
Type '((...strings: string[]) => string) | { (...items: ConcatArray<string>[]): string[]; (...items: (s...'
has no compatible call signatures.
Run Code Online (Sandbox Code Playgroud)
因为它们有不同的返回类型?但我认为 TS 可以推断出error的类型是S. 是有意设计吗?如果是,为什么?
因为虽然concat方法在两种类型之间是通用的,但两者之间的签名非常不同,所以 Typescript 无法真正合并方法的声明。虽然不理想,但您可以使用类型保护来区分这两种类型:
const s: string = 'foo';
type S = string | string[];
const error = (origin: S) => typeof origin === 'string' ?
origin.concat(s) :
origin.concat(s);
Run Code Online (Sandbox Code Playgroud)
或者只是断言为any:
const s: string = 'foo';
type S = string | string[];
const error = (origin: S) => (origin as any).concat(s) as S
Run Code Online (Sandbox Code Playgroud)
还可以选择将签名的并集转换为签名的交集。这在某些情况下可能很有效,但在其他情况下可能无效:
const s: string = 'foo';
type S = string | string[];
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
function mergeSignature<T, K extends keyof T> (value: T, method: K) : UnionToIntersection<T[K]>{
return ((...args: any[]) => (value[method] as any as Function).apply(value, args)) as any;
}
const error = (origin: S) => mergeSignature(origin, 'concat')(s);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1246 次 |
| 最近记录: |