【发布时间】:2020-11-25 20:48:27
【问题描述】:
我一直在努力解决定义类型的一个有趣的问题。 由于我正在学习 TS,请记住,我也在寻找解释或参考。
根据标题,我有一个函数定义为:
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 限制为 keyof ChildObj 而 ParentObj 没有。
提前感谢您的帮助和解释!
【问题讨论】:
-
标题很误导
标签: typescript types typescript-typings typescript-generics union-types