gpt4 book ai didi

typescript - 如何将已知的接口(interface)属性与自定义索引签名相结合?

转载 作者:行者123 更新时间:2023-12-01 09:46:27 25 4
gpt4 key购买 nike

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

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

最佳答案

所有者(直到现在)接受的问题是不正确的。
以下是您的操作方法:
您需要使索引签名成为接口(interface)中可以包含的所有类型的联合类型:

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
}

关于typescript - 如何将已知的接口(interface)属性与自定义索引签名相结合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com