Last active
October 25, 2018 14:59
-
-
Save uonr/5020134babff3542192ec4ca1e063076 to your computer and use it in GitHub Desktop.
return a type by pass this type‘s name
This file contains 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
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); |
This file contains 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
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(''); |
This file contains 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
// 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