[英]How to express “the types of the values under all existing keys are of some type” in generic constraints in TypeScript?
最自然的想法似乎是
interface Generic<T extends {[key: string]: string | undefined}> {
}
interface Simple {
id?: string;
}
function dummy(param: Generic<Simple>): any {}
但這是行不通的。 但是,這是可以理解的,因為對象a: Simple
可能具有其他字段,其鍵可能不是string
類型。
有用的一種可能情況是“查詢參數都是字符串”,因此我們希望req.query
的類型為{[key: string]: string | undefined}
{[key: string]: string | undefined}
。 使用對象執行此操作沒有問題。 但是,如果我們想從“ express”中擴展定義,並在通用約束中使用它:
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:類型'DummyQueries'不滿足約束'{{鍵:字符串]:字符串| 未定義 }'。 類型'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 {}
( 操場上的代碼 )
類型檢查在接口的定義中失敗,而不是在將其用作Generic
的泛型類型時失敗,但是如果我理解要實現的結果,結果是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.