英文:
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];
英文:
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<T> = {
[K in keyof T]: {
header: string;
accessor: K;
render?: (value: T[K], original: typeof originalObj) => React.ReactNode;
};
}[keyof T];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论