我想生成一个类型 Response
type Response =
{
code: 200
body: {
msg: string
}
} | {
code: 400
body: {
errorCode: number
}
}
来自Foo
(由生成的类型的简化版本。
interface Foo {
200: {
msg: string
}
400: {
errorCode: number
}
}
我在下面尝试过,但是没有用。
type Response = {
code: keyof Foo // 200 | 400
body: Foo[keyof Foo] // {msg: string} | {errorCode: number}
}
const res: Response = {
code: 200,
body: {
errorCode: 1 // not get an error
}
}
有人能帮我吗?
现在,您正在将所有可能的code
类型与所有可能的body
类型混合在一起。您需要使用映射类型来显式遍历的每个键K
,Foo
并使每个元素成为K
键和Foo[K]
值的函数。这将产生一个新的对象类型{200: {code: 200, ...}, 400: {code: 400, ...}
,您需要查找该对象类型以获取其属性的并集:
type Resp = { [K in keyof Foo]: { code: K, body: Foo[K] } }[keyof Foo];
/* type Resp = {
code: 200;
body: {
msg: string;
};
} | {
code: 400;
body: {
errorCode: number;
};
} */
(我将其重命名,Resp
因为已经有一个Response
我不想与之发生冲突的全局范围)。
然后body
,在给定的条件下使用错误时,您将得到所需的错误code
:
const res: Resp = {
code: 200,
body: {
errorCode: 1 // error!
// ~~~~~~~~~~~~
// Type '{ errorCode: number; }' is not assignable to type '{ msg: string; }'.
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句