[英]Typescript: Define a type T such that T & {'a': any} == R
在定義類型時,我一直在努力解決一個有點有趣的問題。 在我學習 TS 時,請記住,我也在尋找解釋或參考。
根據標題,我有一個 function 定義為:
function make<ChildObj extends ParentObj, ParentObj, Missingkey extends string>(
parentObj: ParentObj, // Only 1 key is missing to make ChildObj become ParentObj
missingKey: MissingKey,
): ChildObj {
const missingKeyValue = Math.random();
doSomething({ // doSomething expects the first parameter to be of type ChildObj
...childObj,
[missingKey]: missingKeyValue
});
}
使用示例:
type ParentObj = {a: any};
type ChildObj = {a: any, b: any};
make<ParentObj, ChildObj, 'x'>({a: 0}, 'x') // Invalid because ParentObj & {'x': any} is not ChildObj
make<ParentObj, ChildObj, 'b'>({a: 0}, 'b') // Valid
所以簡而言之,我需要將missingKey
限制為ParentObj
沒有的ChildObj
的 1 keyof
。
在此先感謝您的幫助和解釋!
您不需要將 Child 指定為通用參數。 make
只返回一個Parent
級和一個帶有額外密鑰的 object 的交集。
function make<T extends object, K extends string>(parent: T, key: K) {
return {
...parent,
[key]: Math.random(),
} as T & { [P in K]: number };
}
const a = make({x: 1}, 'y'); // type: {x: number} & {y: number}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.