Using typescript, is it possible to infer object keys from function argument values?

32 views Asked by At

Take this string parsing function as an example.

  
  const { a, b } = parseString({
    string, 
    mapping: [{
      param: 'a',
      ...
    },{
      param: 'b',
      ...
    }]

Can i make typescript be aware that the only available keys should be 'a' and 'b'?

These are the types that I currently have.

interface ParseStringArgs {
    string: string;
    mapping: {
        start: string | null;
        end: string | null
        param: string;
    }[];
}

And my attempt at making it read the param key value. Which obviously does not work now as it is (correctly) reading param: string; from the ParseStringArgs interface above.

export function parseString({ string, mapping }) {

...

    type ParamKey = typeof mapping[number]['param'];
    const result: Record<ParamKey, string> = {};

    ... some logic to populate result

    return result

Now the result of the parseString is Record<string, string>

Is it possible to make the return type of the function Record<'a' | 'b', string>?

0

There are 0 answers