Skip to content

Instantly share code, notes, and snippets.

@uonr
Last active October 25, 2018 14:59
Show Gist options
  • Save uonr/5020134babff3542192ec4ca1e063076 to your computer and use it in GitHub Desktop.
Save uonr/5020134babff3542192ec4ca1e063076 to your computer and use it in GitHub Desktop.
return a type by pass this type‘s name
export type Name = { name: string }
export type Id = { id: number }
type Get<T extends string> =
T extends "Name" ? Name :
T extends "Id" ? Id :
never
function get<T extends string>(x: T): Get<T>;
function get(x: string) {
if (x === "Name")
return { name: "Homura" };
else
return { id: 42 };
}
get("Name").name.charAt(1);
get("Id").id.toExponential(1);
export type Name = { name: string, tag: "Name" }
export type Id = { id: string, tag: "Id" }
type Sum = Name | Id;
type Filter<T, U> = T extends U ? T : never;
type FilterTag<T, U extends string> = Filter<T, {tag: U}>;
function get<T extends string>(x: T): FilterTag<Sum, T>;
function get(x: string) {
if (x === "Name")
return { name: "Homura", tag: x };
else
return { id: "42", tag: x };
}
get("Name").name.charAt(1);
get("Id").id.concat('');
// https://stackoverflow.com/questions/45933462/string-literal-argument-as-compile-time-type-name
declare namespace Sum {
export class Name {
name: string;
}
export class Age {
age: number;
}
}
function get<K extends keyof typeof Sum>(key: K): (typeof Sum)[K]['prototype'] {
if (key === "Name")
return new Sum.Name();
else
return new Sum.Age();
}
get('Name').name.concat('a');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment