Typescript 索引类型的条件开关

Typescript 索引类型的条件开关,typescript,conditional-types,Typescript,Conditional Types,我想设置一个条件,如果传入的类型具有索引签名,则该条件将触发。到目前为止,这就是我所拥有的: 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: s

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

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"'.
type IsIndexed=T扩展{[key in string]:any}?
“类型已编制索引”:
“类型未编入索引”;
常量a:IsIndexed=“类型未索引”;
常量b:IsIndexed=“类型已索引”;
常量c:IsIndexed=“类型未索引”//类型“类型未索引”不可分配给类型“类型已索引”。

从注释中可以看出,存在一种类型错误,因为TypeScript似乎认为没有明确索引索引的对象类型是那些有一个的索引类型的子集。 这是有道理的——如果我编写一个函数,它只需要运行一个带有

string
键和
boolean
值的对象,那么没有理由不能将一个符合该形状并带有显式命名键的对象传递给它,但就我而言,这还不够


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

是的,您可以通过测试
string
是否是
T
类型的
keyof T
的子类型来完成此操作。如果是,则所有字符串都是有效键;如果不是,则密钥仅限于一组有限的密钥名称

类型索引={[k:string]:number};
类型notindex={x:number,y:number};
类型Detect=字符串扩展了KEYT?'索引':'未索引';
类型TestIndexed=Detect;/'索引'
类型TestNotIndexed=Detect;//'未编入索引'

是的,您可以通过测试
string
是否是
T
类型的
keyof T
的子类型来完成此操作。如果是,则所有字符串都是有效键;如果不是,则密钥仅限于一组有限的密钥名称

类型索引={[k:string]:number};
类型notindex={x:number,y:number};
类型Detect=字符串扩展了KEYT?'索引':'未索引';
类型TestIndexed=Detect;/'索引'
类型TestNotIndexed=Detect;//'未编入索引'

有点让我震惊,我认为这是可行的——我完全准备好接受这次失败。谢谢有点让我震惊,我认为这是可行的——我完全准备好接受这次失败。谢谢