gpt4 book ai didi

typescript - 索引类型的条件开关

转载 作者:行者123 更新时间:2023-12-03 08:46:36 24 4
gpt4 key购买 nike

我想设置一个条件,如果传入其中的类型具有索引签名,则触发该条件。到目前为止,这就是我所拥有的:

type IsIndexed<T> = T extends {[key in string]: any} ?
"type is indexed" :
"type is not indexed";

const a: IsIndexed<boolean> = "type is not indexed";
const b: IsIndexed<{ [key: string]: number }> = "type is indexed";
const c: IsIndexed<{ prop: string }> = "type is not indexed"; // Type '"type is not indexed"' is not assignable to type '"type is indexed"'.

正如您从注释中看到的,存在类型错误,因为 TypeScript 似乎将没有明确索引签名的对象类型视为具有明确索引签名的对象类型的子集。

这是有道理的 - 如果我编写一个函数,并且它需要运行的只是一个带有 string 键和 boolean 值的对象,那么没有理由让对象适合该形状带有明确命名的键不能传递给它,但对于我的目的来说,这还不够。

是否可以编写一个条件类型来标识与显式命名键不同的索引签名

最佳答案

是的,您可以通过测试string是否是T类型的keyof T的子类型来做到这一点。如果是,则所有字符串都是有效键;如果不是,那么这些键将被限制为一组有限的键名称。

type Indexed = { [k: string]: number };
type NotIndexed = { x: number, y: number };

type Detect<T> = string extends keyof T ? 'Indexed' : 'Not Indexed';

type TestIndexed = Detect<Indexed>; // 'Indexed'
type TestNotIndexed = Detect<NotIndexed>; // 'Not Indexed'

Playground Link

关于typescript - 索引类型的条件开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61239225/

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