Last active
December 20, 2019 10:07
-
-
Save RubaXa/cdd9a83695bb589eb414bde21fa8e056 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ObjectFromTuple<T extends string[]> = | |
FlattenObject< // 5. Делаем объект плоским | |
ToIntersect< // 4. Union to Intersection | |
{ // 2. { [key]: { [value]: value } } | |
[K in keyof T]: T[K] extends string | |
? Record<T[K], T[K]> // 1. { [value]: value } | |
: never | |
}[number] // 3. { [key]: { [value]: value } } -> { [value]: value } & { [value]: value } | |
> | |
> | |
; | |
function createObjectFromTuple<T extends string[]>(...tuple: T) { | |
return tuple.reduce((obj, key) => { | |
obj[key] = key; | |
return obj; | |
}, {} as ObjectFromTuple<T>); | |
} | |
// Проверяем | |
const result = createObjectFromTuple('foo', 'bar', 'qux'); | |
// typeof result: | |
// { | |
// foo: "foo"; | |
// bar: "bar"; | |
// qux: "qux"; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment