Search code examples
typescripttypesinterfacestring-parsing

Typescript dynamic interface from object values


I am creating args parser from a string. I have interface for defining args names and default values

interface IargsDef {
    name: string;
    default?: string;
}

What I want is for intellisense(make some dynamic interface idk) works with parse result.

For args def

[{
name: "test1"
}, 
{
name: "test2", 
default: "test"
}]

It woult be look like that

{
"test1": "some value",
"test2": "some value or default"
}

But intellisense will not see these properties.


Solution

  • If I've understood what you're looking for correctly, then something like this might do the trick:

    interface IArgsDef<Name extends string> {
        name: Name;
        default?: string;
    }
    
    const argsDef = {
      test1: { name: "test1" },
      test2: { name: "test2", default: "test" }
    }
    
    type ArgsInput<Defs extends Record<string, unknown>> = Defs[keyof Defs] extends IArgsDef<infer _>
      ? Record<keyof Defs, string>
      : never
    
    type ExpectedInput = ArgsInput<typeof argsDef>
    // type ExpectedInput = {
        // test1: string;
        // test2: string;
    }
    

    I changed the way your args definition is defined from an array to an object in order to make this work though, which I'm not sure is acceptable or not.