【发布时间】:2020-09-18 04:04:49
【问题描述】:
我被困在一个函数的类型定义上,该函数接受包含鉴别器的泛型。
我需要的是确保函数始终返回MyType,这与泛型内部类型的细节无关,但我希望这是“推断”的。例如。我不必写我要返回的特定MyType,因为它将“合并”(甚至替换)返回值
例如,这里我收到一个包含 3 个 MyType 相关类型的类型,但只返回 2 个。
interface MyType <Tag, Type> {
tag: Tag;
value: Type;
}
type SampleInputType = MyType<'a number', number> | MyType<'a string', string> | MyType<'foo', boolean>;
const sampleInputValue: SampleInputType = {
tag: 'a number',
value: 10
};
// Ideally would like to accept any MyType<W, X> and return any MyType<Y, Z>
// But not MyType<any, any>
// Would be fine with only the return type
const myFunction = (input) => {
if (input.tag === 'a number') {
return {
tag: 'foo',
value: true
};
} else {
return {
// Sample of type mistaked i would like to avoid, as this convert the return value to any silently
tagx: 'a number', // This should be a compiler error
value: 10
}
}
};
// Sample output type
type SampleOutputType = MyType<'a number', number> | MyType<'foo', boolean>;
// myVal only posibilities should only be MyType<'a number', number> and MyType<'foo', boolean>
const myVal = myFunction(sampleInputValue);
if (myVal.tag === 'foo') {
const b: boolean = myVal.value; // this is any :/
}
【问题讨论】:
标签: typescript typescript-generics