如何表达"所有现有键下的值的类型是某种类型的#34;在TypeScript中的泛型约束?

时间:2016-08-18 07:56:51

标签: generics typescript

最自然的想法似乎是

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

}

interface Simple {
    id?: string;
}

function dummy(param: Generic<Simple>): any {}

但这不起作用。但是,这是可以理解的,因为对象a: Simple可能有其他字段,其键可能不是string类型。

有用的一种可能情况是&#34;查询参数都是字符串&#34;,因此我们希望req.query的类型为{[key: string]: string | undefined}。使用对象执行此操作没有问题。但是,如果我们想要扩展定义,例如,来自&#34; express&#34;,并在通用约束中使用它:

export interface RequestWithQuery<T extends {[key: string]: string | undefined}> extends Request {
    /**
     * The custom typed query.
     */
    query: T;
}

interface DummyQueries { input?: string; }

function dummyController(req: RequestWithQuery<Dummy>, res: Response) {}

会出现以下错误:

  

错误TS2344:输入&#39; DummyQueries&#39;不满足约束&#39; {[key:string]:string |不确定的; }&#39 ;.     类型&#39; DummyQueries&#39;。

中缺少索引签名

问题实际上归结为表达&#34; 完全这些字段&#34;而不是&#34;至少包含这些字段&#34;我认为。但是在TypeScript中可以吗?

1 个答案:

答案 0 :(得分:2)

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

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 {}

code in playground

类型检查在界面定义中失败,而不是在将其用作Generic的泛型类型时,但结果是相同的,如果我理解你想要实现的目标。