Created
August 5, 2019 16:01
-
-
Save iwillwen/0bbb4a6643bfca7ee573c93a1fa24506 to your computer and use it in GitHub Desktop.
TypeScript ImferredOptionType
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
interface Options { | |
type: "boolean" | "number" | "string" | "array"; | |
} | |
type InferredOptionType<O extends Options> = | |
O extends { type: "array" } ? Array<string | number> : | |
O extends { type: "boolean" } ? boolean : | |
O extends { type: "number" } ? number : | |
O extends { type: "string" } ? string : | |
unknown; | |
type Result<T = {}> = T & { | |
[key: string]: unknown | |
} | |
class OBJ<T> { | |
add<K extends string, O extends Options>(key: K, options: O) { | |
return new OBJ<T & { [key in K]: InferredOptionType<O> }>() | |
} | |
get result() { | |
return {} as { [key in keyof Result<T>]: Result<T>[key] } | |
} | |
} | |
const obj = new OBJ() | |
obj | |
.add('foo', { | |
type: 'array' | |
}) | |
.add('bar', { | |
type: 'string' | |
}) | |
.add('test', { | |
type: 'number' | |
}) | |
.result | |
.bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment