Created
December 20, 2019 10:30
-
-
Save RubaXa/f925dc837815695d33a8f7ae80339377 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 Primitive = string | number | boolean | null; | |
type Token<N extends string, V extends Primitive> = { | |
name: N; | |
value: V; | |
} | |
type TokensDict<T extends Token<any, any>[]> = | |
FlattenObject< | |
ToIntersect< | |
{ | |
[K in keyof T]: T[K] extends Token<infer N, any> | |
? Record<N, T[K]> // INFER всему голова! | |
: never | |
}[number] | |
> | |
> | |
; | |
// Фабрика токенов | |
function createToken< | |
N extends string, | |
V extends Primitive | |
>(name: N, value: V): Token<N, V> { | |
return {name, value}; | |
} | |
// Функция создание словаря токенов | |
function createTokensDict<T extends Token<any, any>[]>(...tokens: T): TokensDict<T> { | |
return tokens.reduce((composite, token) => { | |
composite[token.name] = token.value; | |
return composite; | |
}, {} as TokensDict<T>) | |
} | |
// Проверяем | |
const result = createTokensDict( | |
createToken('foo', '123'), | |
createToken('bar', true), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment