如何将声明的接口属性与自定义索引签名相结合

时间:2017-12-01 11:37:29

标签: typescript

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

this.SQLObj.executeSql("SELECT * from Calls WHERE date(Calls.CallDate) = date(?1)", '2017-11-30').then(res => { console.log(res); })

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

{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 )要求所有密钥都是索引签名类型的子集(在这种情况下是返回布尔值的函数)。这显然失败了。

2 个答案:

答案 0 :(得分:4)

这不可能,按设计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

重要这只是为了科学,我不建议将其作为现实生活方式!

答案 1 :(得分:1)

所有者接受的问题(直到现在)是不正确的。

以下是如何做到的:

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

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
}