[英]How to convert a mapped generic type to an union of tuples in typescript
I'm creating something similar to Object.entries
and I would like it to be more strongly typed. 我正在创建类似于
Object.entries
东西,我希望它被更强地键入。 I want to make a type which given an object returns strongly typed union of 2-tuples of that object's properties. 我想创建一个给定对象返回该对象属性的2元组的强类型联合的类型。
Currently 目前
export type Entries<T> = [keyof T, T[keyof T]][];
Entries<{first: number, second: string}> = ["first" | "second", number | string][]
What I would like 我想要什么
Entries<{first: number, second: string}> = ["first", number] | ["second", string][]
You should use an actual mapped type with the {[K in keyof T]: ...}
syntax, and then look up its properties: 您应该使用带有
{[K in keyof T]: ...}
语法的实际映射类型 ,然后查找其属性:
export type Entries<T> = { [K in keyof T]: [K, T[K]] }[keyof T][];
type E = Entries<{ first: number; second: string }>;
// type E = (["first", number] | ["second", string])[]
You could also use a distributive conditional type like this one that requires a helper type alias to work: 您还可以使用像这样的分布式条件类型 ,它需要一个辅助类型别名才能工作:
type EntriesHelper<T, K> = K extends keyof T ? [K, T[K]] : never;
type Entries<T> = Array<EntriesHelper<T, keyof T>>;
type E = Entries<{ first: number; second: string }>;
// type E = (["first", number] | ["second", string])
or like this one that uses inference in conditional types instead of a helper: 或像这样在条件类型中使用推断而不是帮助器的对象:
type Entries<T> = Array<
keyof T extends infer K ? (K extends keyof T ? [K, T[K]] : never) : never
>;
type E = Entries<{ first: number; second: string }>;
// type E = (["first", number] | ["second", string])[]
They all produce the same output here, but might act differently in the face of optional properties or other edge case, so be careful. 它们在这里都产生相同的输出,但是面对可选属性或其他边缘情况时,它们的行为可能有所不同,因此请小心。 Hope that helps;
希望能有所帮助; good luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.