Generics 如何表达;所有现有键下的值类型都属于某种类型;在TypeScript中的泛型约束中?

Generics 如何表达;所有现有键下的值类型都属于某种类型;在TypeScript中的泛型约束中?,generics,typescript,Generics,Typescript,最自然的想法似乎是 interface Generic<T extends {[key: string]: string | undefined}> { } interface Simple { id?: string; } function dummy(param: Generic<Simple>): any {} 会出现以下错误: 错误TS2344:类型“DummyQueries”不满足约束“{[key:string]:string | undefin

最自然的想法似乎是

interface Generic<T extends {[key: string]: string | undefined}> {

}

interface Simple {
    id?: string;
}

function dummy(param: Generic<Simple>): any {}
会出现以下错误:

错误TS2344:类型“DummyQueries”不满足约束“{[key:string]:string | undefined;}”。 类型“DummyQueries”中缺少索引签名


我认为,问题实际上归结为表达“拥有这些字段”,而不是“至少拥有这些字段”。但是在TypeScript中是否可能呢?

您可以做一些足够接近的事情:

interface Base {
    [key: string]: string;
}

interface Generic<T extends Base> {}

interface Ok extends Base {
    id?: string;
}

interface NotOk extends Base {
    id?: string;
    num?: number; // error: Property 'num' of type 'number' is not assignable to to string index type `string`
}

function dummy(param: Generic<Ok>): any {}
接口基础{
[键:字符串]:字符串;
}
接口通用{}
接口Ok扩展了基础{
id?:字符串;
}
接口NotOk扩展了基础{
id?:字符串;
num?:number;//错误:“number”类型的属性“num”不能分配给字符串索引类型“string”`
}
函数dummy(param:Generic):任意{}
()


类型检查在接口定义中失败,而不是在将其用作
generic
的泛型类型时失败,但如果我理解您想要实现的目标,结果是一样的。

您可以做一些足够接近的事情:

interface Base {
    [key: string]: string;
}

interface Generic<T extends Base> {}

interface Ok extends Base {
    id?: string;
}

interface NotOk extends Base {
    id?: string;
    num?: number; // error: Property 'num' of type 'number' is not assignable to to string index type `string`
}

function dummy(param: Generic<Ok>): any {}
接口基础{
[键:字符串]:字符串;
}
接口通用{}
接口Ok扩展了基础{
id?:字符串;
}
接口NotOk扩展了基础{
id?:字符串;
num?:number;//错误:“number”类型的属性“num”不能分配给字符串索引类型“string”`
}
函数dummy(param:Generic):任意{}
()

类型检查在接口定义中失败,而不是在将其用作
generic
的泛型类型时失败,但是如果我理解您想要实现的目标,结果是一样的