Skip to content

Instantly share code, notes, and snippets.

@hasparus
Last active June 28, 2019 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hasparus/82e81d9a389fb8bc75c46c14a4551ec0 to your computer and use it in GitHub Desktop.
Save hasparus/82e81d9a389fb8bc75c46c14a4551ec0 to your computer and use it in GitHub Desktop.
const questions = [
{
message: 'Enter your login (email address)...',
name: 'login',
type: 'input',
},
{
message: 'Enter your password...',
name: 'password',
type: 'password',
},
] as const;
type Input = string & { __brand: 'Input' };
type Password = string & { __brand: 'Password' };
type QuestionTypeToValueType = {
input: Input;
password: Password;
price: number;
}
type Question = {
readonly message: string;
readonly name: string;
readonly type: string;
}
type Answer<Q extends Question> = {[P in Q['name']]: Q['type']};
/**
* type X = { login: "input" };
*/
type X = Answer<{ message: '', name: 'login', type: 'input' }>;
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type Simplify<T> = Pick<T, keyof T>
type Answers<Qs extends readonly Question[]> = Simplify<UnionToIntersection<{
[I in keyof Qs]: Qs[I] extends Qs[number] ? Answer<Qs[I]> : never;
}[number]>>
/**
* type Y = {
* login: 'input';
* password: 'password';
* }
*/
type Y = Answers<typeof questions>;
// type Z = {
// login: Input;
// password: Password;
// }
type Z = { [K in keyof Y]: QuestionTypeToValueType[Y[K]] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment