如何从另一种类型派生出一个区分联合?

huangapple go评论109阅读模式
英文:

How to derive a discriminated union from another type?

问题

以下是您要求的翻译:

让我们假设我们有一个类型为的对象
如何编写一个实用程序类型以从原始对象创建一个具有以下外观的辨别联合
如果我手动创建它我想要的会看起来像
如何编写一个辅助函数当只提供原始对象类型时自动为我创建这个
英文:

Let's say we have an object of type

const originalObj = { foo: 'fooVal', bar: 'barVal' };

How do I write a utility type to create a discriminated union from the original object so that each member would look like

type Sample1 = {
  header: string;
  accessor: 'foo' //discriminant
  render?: (value: 'fooVal', original: typeof originalObj) => React.ReactNode;
};

type Sample2 = {
  header: string;
  accessor: 'bar' //discriminant
  render?: (value: 'barVal', original: typeof originalObj) => React.ReactNode;
};

If I created it manually, what I want would would look like

type OriginalObjMappedToUnIonOfSamples = Sample1 | Sample2;

How do I write a helper to automatically create this for me when only given the original object type? Maybe something like

type WhatIWant = GetDiscriminatedUnionOfSamples<typeof originalObj>;

答案1

得分: 1

你可以使用一个映射类型,将originalObj中的每个键映射到其相应的对象类型。使用keyof T索引结果将产生你所寻找的结果。

type GetDiscriminatedUnionOfSamples<T> = {
  [K in keyof T]: {
    header: string;
    accessor: K;
    render?: (value: T[K], original: typeof originalObj) => React.ReactNode;
  };
}[keyof T];

Playground

英文:

You can use a mapped type which maps each key in originalObj to its corresponding object type. Indexing the result with keyof T will produce the result you are looking for.

type GetDiscriminatedUnionOfSamples&lt;T&gt; = {
  [K in keyof T]: {
    header: string;
    accessor: K;
    render?: (value: T[K], original: typeof originalObj) =&gt; React.ReactNode;
  };
}[keyof T];

Playground

huangapple
  • 本文由 发表于 2023年2月16日 10:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定