Lucian
Lucian

Reputation: 49

How to define the value type for example

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
}

for this example, how to define ParamsProps correctly?

expect to the right way and editor auto prompt the type only can be string.


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

Will someone help me?

Exapmle TS Playground

Upvotes: 1

Views: 369

Answers (1)

AlienWithPizza
AlienWithPizza

Reputation: 446

When in doubt, add more generics!

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

Upvotes: 1

Related Questions