【发布时间】:2020-03-20 09:30:14
【问题描述】:
我正在使用打字稿,我定义了以下接口:
export interface BaseProtocol {
[key: string]: (payload: unknown) => Promise<unknown>;
}
现在我想定义一个协议:
import { BaseProtocol } from './BaseProtocol';
export interface AppProtocol extends BaseProtocol {
action(payload: string): Promise<string>;
}
不幸的是,我收到以下错误:
Property 'action' of type '(payload: string) => Promise<string>' is not assignable to string index type '(payload: unknown) => Promise<unknown>'.ts(2411)
我不愿意使用任何,因为它损害了协议使用的类型安全。 知道如何解决这个问题吗?
【问题讨论】:
-
type AppProtocol = { action(payload: string): Promise<string>; } & BaseProtocol; -
有什么区别?
-
这是一个 TS 类型系统的怪癖,不确定它是否记录在任何地方,但应该这样做。
-
但是这给了我一个错误:
const a:Protocol = { action(payload: string){ return new Promise<string>((resolve)=>resolve() ); };: Type 'unknown' is notassignable to type 'string'。 -
哦,那真是令人惊讶,它应该可以工作。让我们看看..
标签: typescript typescript-generics