如何将已知接口属性与自定义索引签名结合起来?

How to combine known interface properties with a custom index signature?

如何键入可以同时具有一些声明的可选属性的对象,例如:

{ 
    hello?: string, 
    moo?: boolean 
}

以及自定义属性(必须是函数),例如:

    [custom: string]: (v?: any) => boolean

这是我希望看到的示例:

const myBasic: Example = {moo: false}
// -> ✅ Valid! Using known keys

const myValid: Example = {hello: 'world', customYo: () => true}
// -> ✅ Valid! "customYo" is a function returning a bool. Good job!

const myInvalid: Example = {hello: 'world', customYo: 'yo!'}
// -> ☠️ Invalid! "customYo" must be a function returning a boolean

尝试将索引签名添加到具有已知键(即 hello?: string, moo?: boolean)的接口需要所有键都是索引签名类型的子集(在这种情况下,函数返回 boolean ).这显然失败了。

这是不可能的,设计使然 https://basarat.gitbooks.io/typescript/docs/types/index-signatures.html

As soon as you have a string index signature, all explicit members must also conform to that index signature. This is to provide safety so that any string access gives the same result.

绕过它的唯一方法是利用每个接口可以有 2 个单独的索引签名,一个用于 stringnumber

在您的示例中,hellomoo 使字符串索引无法使用,但您可以为自定义方法劫持数字索引

interface IExample {
  hello?: string
  moo?: boolean
  [custom: number]: (v?: any) => boolean
}

const myBasic: IExample = {moo: false}
// -> ✅ Valid! Using known keys

const myValid: IExample = {hello: 'world', 2: () => true}
// -> ✅ Valid! "customYo" is a function returning a bool. Good job!

const myInvalid: IExample = {hello: 'world', 2: 'yo!'}
// -> ☠️ Invalid! "customYo" must be a function returning a boolean

这可行,但几乎不是一个可接受的接口,因为它会导致不直观的函数,您将不得不通过数组表示法调用它们

myValid.7() // Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures.
myValid[2]() // works (but ewwwww what is this!!!)
// could alias to more readable locals later but still ewwwwww!!! 
const myCustomFunc = myValid[2]
myCustomFunc() // true

这也有一个警告,即从数字索引器返回的类型必须是从字符串索引器返回的类型的子类型。这是因为当使用数字进行索引时,javascript 会在索引到对象之前将数字转换为字符串

在这种情况下,您没有明确的字符串索引器,因此字符串索引类型是默认值 any,数字索引器类型可以符合

重要这只是为了科学,我不推荐将其作为现实生活的方法!

楼主所接受的问题(到现在为止)是不正确的。

你可以这样做:

您需要将索引签名设为接口中可以包含的所有类型的联合类型:

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
}