gpt4 book ai didi

typescript - 扩展索引 typescript 接口(interface)

转载 作者:搜寻专家 更新时间:2023-10-30 21:17:11 24 4
gpt4 key购买 nike

考虑一个简单的索引接口(interface):

interface FormData {
[K: string]: string;
}

那个小家伙工作得很好。但是,在某些情况下,我希望允许属性为字符串数组。

interface AcmeFormData extends FormData {
foobar: string[];
}

typescript 提示

Property 'foobar' of type 'string[]' is not assignable to string index type 'string'.

查看文档,似乎以下应该是可能的,但也有提示。

interface FormData {
[K: string]: string;
foobar: string[];
}

应该注意的是,我想避免使用联合类型 ([K: string]: string | string[];) 因为 99% 的时间,数据总是是单个字符串值,因此希望避免键入提示。

这可能吗?还是我想滥用 Typescript?

最佳答案

您可以使用交集而不是使用extends 来做到这一点。例如:

interface FormData {
[K: string]: string;
}

type AcmeFormData = FormData & { foobar: string[] };

declare const test: AcmeFormData;

test.foobar // string[]
test.anythingelse // string

但是,这确实会导致一些您需要注意的问题,因为现在索引签名不再准确。因此,当 typescript 使用该签名推断某些内容时,您需要意识到它是错误的:

for (let key in test) {
// val is inferred to have type string, but be careful!
// In truth, val will be a string[] for the 'foobar' key,
// but typescript is no longer aware of that. So this will
// create a runtime error, but compiles without problems!

const val = test[key].toLowerCase();
}

关于typescript - 扩展索引 typescript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52788045/

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