Skip to content

Instantly share code, notes, and snippets.

@iwillwen
Created August 5, 2019 16:01
Show Gist options
  • Select an option

  • Save iwillwen/0bbb4a6643bfca7ee573c93a1fa24506 to your computer and use it in GitHub Desktop.

Select an option

Save iwillwen/0bbb4a6643bfca7ee573c93a1fa24506 to your computer and use it in GitHub Desktop.

Revisions

  1. iwillwen created this gist Aug 5, 2019.
    41 changes: 41 additions & 0 deletions types.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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