例如如何定义值类型

How to define the value type for example

示例:


type ObjProps = {
  a: string;
  b: string[] | null;
};

type ValueOf<T> = T[keyof T];

const obj: ObjProps = {
  a: 'test',
  b: null
};

type ParamsProps = {
  propName: keyof ObjProps;
  value: ValueOf<ObjProps>;
}

const updateFn = ({
 propName, 
 value
}: ParamsProps): void => {
  obj[propName] = value; // ts error
}

对于这个例子,如何正确定义ParamsProps?

期待正确的方式和编辑器自动提示类型只能是字符串。


updateFn({
  propName: 'a',
  value: 'update' // editor auto prompt the type only can be string
});

有人会帮助我吗?

Exapmle TS Playground

如有疑问,请添加更多泛型!

type ObjProps = {
  a: string;
  b: string[] | null;
};

const obj: ObjProps = {
  a: 'test',
  b: null
};

type ParamsProps<TKey extends keyof ObjProps> = {
  propName: TKey;
  value: ObjProps[TKey];
}

const updateFn = <TKey extends keyof ObjProps>({ propName, value }: ParamsProps<TKey>): void => {
  obj[propName] = value;
}

updateFn({propName: 'a', value: "test"});
updateFn({propName: 'b', value: ["test"]});
updateFn({propName: 'b', value: null});
updateFn({propName: 'a', value: ["test"]}); // ts error