所有者(直到现在)接受的问题是不正确的。
以下是您的操作方法:
您需要使索引签名成为接口中可以包含的所有类型的联合类型:
interface IExample {
hello?: string;
moo?: boolean;
[custom: string]: string | boolean | YourFunctionType;
}
interface YourFunctionType {
(v?: any): boolean;
}
请注意,我已将您的函数类型提取到单独的界面中以提高可读性。
影响:
这意味着,明确定义的属性得到 TS 的良好支持:
const test: IExample = <IExample>{};
test.hello.slice(2); // using a string method on a string --> OK
const isHello = test.hello === true; // ERROR (as expected): === cannot be applied to types string and boolean
const isMoo2 = test.moo === true; // OK
然而,索引签名中的所有属性现在都需要使用类型保护来检查,这会增加一点运行时开销:
test.callSomething(); // ERROR: type 'string | boolean | YourFunctionType' has no compatible call signatures
if (typeof test.callSomething === 'function') { // alternatively you can use a user defined type guard, like Lodash's _.isFunction() which looks a little bit nicer
test.callSomething(); // OK
}
另一方面:运行时开销是必要的,因为它可能是这样test
访问的:
const propertyName: string = 'moo';
test[propertyName](); // ERROR: resolves to a boolean at runtime, not a function ...
// ... so to be sure that an arbitrary propertyName can really be called we need to check:
const propertyName2: string = 'arbitraryPropertyName';
const maybeFunction = test[propertyName2];
if (typeof maybeFunction === 'function') {
maybeFunction(); // OK
}