'Typescript: how to define generic for object to constraint value type in different multiple key

My goal is to constraint data and follow details:

  1. if not specify key, data should has default key with specify type value.
    In this case , if not specify option.stringKey, data should includes 'StringKey' ant value should be string, and if not specify option.numberKey, data should includes 'value' ant value should be number

  2. if option.stringKey is exist, keys of data should includes the option.stringKey and correlative value type should be string. The same as the option.numberKey.

  3. option.numberKey support to be string | string[]. When it's string array, the correlative value type array should be number[].

Follow it's the imperfect code. But miss function to constraint data default type when not specify option.

const test = <
  T extends Record<keyof K, number> & { [_ in U]: string },
  K extends string | string[],
  U extends PropertyKey
>(
  data: T,
  option?: { stringKey?: U; numberKey?: K }
) => {
  const stringKey = option?.stringKey ?? 'StringKey';
  const stringValue = data[stringKey] // type should be string but it error now;
  const numberKeys = option?.numberKey
    ? Array.isArray(option.numberKey)
      ? option.numberKey
      : [option.numberKey as string]
    : ['value'];
  const numberValue = numberKeys.map((numberKey) => data[numberKey]); // type should be number[] ant it's number[]
  console.log(data, option?.stringKey, option?.numberKey);
};
test({ sss: 12, ssd: 223, s1: 'sss' }, { stringKey: 'sss' });


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source