【问题标题】:Typescript: Define a type T such that T & {'a': any} == R打字稿:定义一个类型 T 使得 T & {'a': any} == R
【发布时间】: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 ChildObjParentObj 没有。

提前感谢您的帮助和解释!

【问题讨论】:

  • 标题很误导

标签: typescript types typescript-typings typescript-generics union-types


【解决方案1】:

您不需要将 Child 指定为通用参数。函数make 只是返回Parent 和带有额外键的对象的交集。

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}

【讨论】:

  • 感谢 Mihályi 的回答,不幸的是,这不起作用,因为 make 是与 ChildObjmake 一起使用的类的一部分,然后调用另一个期望类型为 ChildObj 的函数.我没有在最初的问题(已编辑)中指定这一点,因为我现在意识到它与答案相关
  • 我不确定,如果make 没有指定任何类型约束,doSomething 怎么能期望任何类型
猜你喜欢
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2020-05-05
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多