将typescript中的联合类型转换为绑定内部类型,而不是所有类型
在typescript中,如何能够绑定联合,而不是联合所有的可能性将typescript中的联合类型转换为绑定内部类型,而不是所有类型,typescript,typescript-typings,Typescript,Typescript Typings,在typescript中,如何能够绑定联合,而不是联合所有的可能性 type A = | { str: 'true'; value: true; } | { str: 'false'; value: false; }; type Transform<I extends A> = { a: I['str']; b: I['value']; }; type B = Transform<A>;
type A =
| {
str: 'true';
value: true;
}
| {
str: 'false';
value: false;
};
type Transform<I extends A> = {
a: I['str'];
b: I['value'];
};
type B = Transform<A>;
const allowed: B = {a: 'true', b: true};
const allowed2: B = {a: 'false', b: false};
const bad: B = {a: 'true', b: false}; // this should be an error
const bad2: B = {a: 'false', b: true}; // this should be an error
如何修复类型函数转换,使“bad”和“bad2”不可能出现?我刚刚将second union的值更改为true,因此该类型不可能出现false
type A =
| {
str: 'true';
value: true;
}
| {
str: 'false';
value: true; // changed this to true
};
type Transform<I extends A> = {
a: I['str'];
b: I['value'];
};
const good: B = {a: 'true', b: true};
const bad: B = {a: 'true', b: false}; // now throwing error
可以使用来保持变换中的联合类型。当您编写以下内容时,TypeScript会推断出通用超类型并删除联合类型:
type AStr = A["str"] // "true" | "false"
type AValue = A["value"] // boolean
示例如何实现它:
type Transform<I extends A> = I extends A ? {
a: I["str"];
b: I["value"];
} : never
// test it
const bad: B = { a: "true", b: false }; // error
const bad2: B = { a: "false", b: true }; // error
谢谢,但我需要保持A型不变,我只想更改转换函数。我在问题中增加了更多的例子