除了“ errors”属性外,我需要返回带有任何键的对象。
我需要使用runtypes来定义类似{[string]: any, errors: never} | {errors: {message: string}[]}
的网络响应。但首先,我想通过类型系统对其进行定义。
type RespSuccess = {
[key: string]: any;
errors: never;
};
type RespError = {
errors: { message: string }[];
};
async function callNetwork<I extends any[], O extends RespSuccess | RespError>(
fn: (...a: I) => O,
...a: I
): Promise<RespSuccess> {
const resp = await fn(...a);
if ("errors" in resp)
throw new Error(resp.errors.map(({ message }) => message).join());
return resp; // Error: Type 'O' is not assignable to type 'RespSuccess'.
}
最奇怪的是在这里:
// after typeguard the resp is still may be RespSuccess
...throw new Error(resp // const resp: O extends RespSuccess | RespError
// but the errors infer well
...throw new Error(resp.errors // (property) errors: {message: string;}[]
除了TypeScript,我会检查我是否完全返回RespSuccess