Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

generics - TypeScript How to make String Union Type to a concrete Obnject Type?

how can i implement this:

type ActionNames = 'init' | 'reset';

type UnionToObj<U> = {/* TODO HERE */}

type Result = UnionToObj<ActionNames>;
// expect type Result to be `{ init: any, reset: any }`

i had written a implementation, but it not work correctly, it meets the union extends covariance problem:

type UnionToObj<U> = U extends string ? { [K in U]: any } : never;
type Result = UnionToObj<'init' | 'reset'>;
// expecting the type Result to be `{ init: any, reset: any }`
// but i got a union object: `{ init: any } | { reset: any }`
// how do i resolve it ?

main problem:

  1. string union type to object type
  2. union's covariance in ts extends clause.
question from:https://stackoverflow.com/questions/65895648/typescript-how-to-make-string-union-type-to-a-concrete-obnject-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a straightforward mapped type:

type UnionToObj<U extends PropertyKey> = { [K in U]: any }

type Result = UnionToObj<ActionNames>;
/* type Result = {
    init: any;
    reset: any;
} */

Here we are constraining U to be key-like instead of checking it via a conditional type. If you really want to do it that way, you can, with a solution like this:

type UnionToObj<U> = [U] extends [PropertyKey] ? { [K in U]: any } : never;

The difference between this and your version is that your version is unintentionally a distributive conditional type. Since you don't want union inputs to become union outputs, you need to prevent conditional type distribution by not having U extends ... directly with a bare type parameter in the checked position. Wrapping the checked type in a one-tuple ([U] extends ...) is enough to turn off union distribution.

Playground link to code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...