Closed
Description
Search Terms
- spread types
- flatten types
Suggestion
Allow known nested object types to be spread & merged.
If you have a type that meets the condition (or something similar) T extends { [P in keyof T]: object }
I want to be able to flatten it like so ...T
which merges all sub-object types into one type.
Use Cases
What do you want to use this for?
To create better types for popular libraries (namely Vuex at the moment). This would also help make typesafe many utility functions which perform this same function of flattening objects.
What shortcomings exist with current approaches?
I don't think it's possible at the moment.
Examples
// simple
type SimpleFlatten<T> = T extends { [P in keyof T]: object } ? ...T : never;
interface SimpleFlattenTest {
a: { b: string, c: number },
meow: { b: number, d: boolean }
}
SimpleFlatten<SimpleFlattenTest>; // { b: string | number, c: number, d: boolean }
SimpleFlatten<{}>; // {}
SimpleFlatten<boolean>; // never
SimpleFlatten<{a:string}>; // never
// advanced, might not be possible (ideally it would be...)
type NestedFlatten<T> = T extends { [P in keyof T]: object }
? ...{ [A in keyof T]: NestedFlatten<T[A]> }
: T;
interface NestedFlattenTest {
a: { b: string, c: number },
meow: { b: number, d: boolean },
nested: {
ignored: { d: string },
taco: { c: string }
}
}
NestedFlatten<NestedFlattenTest>; // { b: string | number, c: number | string, d: boolean | string }
NestedFlatten<{}>; // {}
NestedFlatten<boolean>; // boolean
NestedFlatten<{a:string}>; // {a: string}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Metadata
Metadata
Assignees
Labels
No labels