class LogFunctionMap {
static error = (err: any) => `[[black]][[bred]]ERROR[[r]] [[white]]${err}`;
static outboundMessage = (message: GGMessage) => ``;
static default = x => x
}
const log = <G extends keyof typeof LogFunctionMap>(loggedObject, logType: G) => {
if (logType) {
const fn: typeof LogFunctionMap[G] = LogFunctionMap[logType];
fn(loggedObject);
}
};
fn(loggedObject);
产生TypeScript错误:
Error:(104, 5) TS2349: This expression is not callable.
Not all constituents of type 'LogFunctionMap | ((err: any) => string) | ((message: GGMessage) => string) | ((x: any) => any)' are callable.
Type 'LogFunctionMap' has no call signatures.
我们看到类型LogFunctionMap
包含在其成员类型的旁边。为什么会这样?
答案 0 :(得分:1)
这是因为除了所有方法之外,<G extends keyof typeof LogFunctionMap>
都包含内置的prototype
方法。来自TypeScript Language Specification:
由类声明引入的构造函数的类型称为构造函数类型。构造函数的类型具有以下成员:
...
- 一个名为“ prototype”的属性,其类型是类型为Any的类类型的实例化,作为每个类型参数的类型实参。
因此,LogFunctionMap.prototype
的类型为LogFunctionMap
。
要消除错误,您可以仅排除prototype
:
const log = <G extends Exclude<keyof typeof LogFunctionMap, "prototype">>(loggedObject, logType: G) => {
if (logType) {
const fn: typeof LogFunctionMap[G] = LogFunctionMap[logType];
fn(loggedObject);
}
};