interface A {
a1: string;
a2: number;
}
interface B {
b1: number;
b2: number;
}
interface Data {
a?: A;
b?: B;
}
const parseA = (x: string): A => ({ a1: '', a2: 0 });
const parseB = (x: string): B => ({ b1: 0, b2: 0 });
const parse = <K extends keyof Data>(name: string, value: string): [K, Required<Data>[K]] => {
switch (name) {
case 'a': return [name, parseA(value)];
case 'b': return [name, parseB(value)];
default: throw new Error('invalid input');
}
}
const test: ['a', A] | ['b', B] = parse('', '');
与case 'a'
(和case 'b'
类似)报告错误:
Type '"a"' is not assignable to type 'K'.
'"a"' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint '"a" | "b"'.(2322)
我认为错误消息没有任何意义。我希望返回值的类型为['a', A]
,因为name
必须在此分支'a'
中,返回对的第二项必须为A
。 'b'
分支也是如此。
我是否在某个地方出错,或者TypeScript编译器不够聪明,无法推断/验证这种约束?可以以类型安全的方式修复/重写它吗?