我正在try 向这个WebSocket协议添加一些类型:
type Action =
| {
action: "change-or-create-state";
response: string;
}
| {
action: "get-state";
response: string | null;
};
/**
* map an action to its response
*/
type ActionResponse<T extends Action["action"]> = Extract<
Action,
{ action: T }
>["response"];
export async function doAction<
TAction extends Action["action"]
>(action: TAction): Promise<ActionResponse<TAction>> { /* ... */ }
我对那些实际上有resolving个promise 的类型有困难,虽然:
// in reality received over websocket
const someDataFromAPI: string = '"hello world"'
export async function doAction<
TAction extends Action["action"]
>(action: TAction): Promise<ActionResponse<TAction>> {
return new Promise<ActionResponse<TAction>>((resolve) => {
// I know I could just keep this as 'any' -- the real code does validation
// which narrows the type.
const jsonWithSpecificType: ActionResponse<TAction> = JSON.parse(someDataFromAPI);
/** ⚠️
Argument of type 'ActionResponse<TAction>' is not assignable to parameter of type 'ActionResponse<TAction> | PromiseLike<ActionResponse<TAction>>'.
Type 'Extract<{ action: "get-state"; response: string | null; }, { action: TAction; }>["response"]' is not assignable to type 'ActionResponse<TAction> | PromiseLike<ActionResponse<TAction>>'.
Type 'string | null' is not assignable to type 'ActionResponse<TAction> | PromiseLike<ActionResponse<TAction>>'.
Type 'null' is not assignable to type 'ActionResponse<TAction> | PromiseLike<ActionResponse<TAction>>'.(2345)
*/
resolve(jsonWithSpecificType)
})
}
Playground link here.我遗漏了什么?显然,any
在这里可以很好地工作,但我只是好奇问题是什么.我的猜测是,它不能保证TAction
在箭头函数内部的类型与在外部函数中的类型相同?