Home > Back-end >  how do i check typeof prop in typescript?
how do i check typeof prop in typescript?

Time:01-27

const test = {
  a: '1',
  b: '2',
  c: '3',
};

type KEYS = keyof typeof test;

const getType = (props: KEYS | string) => {
 const receivedType =
    test[props] === typeof test
      ? test[recordType]
      : '4';
}

i want to check if props is typeof test i will return test[props] but props doesn't include typeof test i want to return 4

I don't know how to deal with the string case.

what is wrong in my code?

CodePudding user response:

If I understood you correctly, you're trying to check if the argument props is a key of the object test. You can't check types during runtime like in test[props] === typeof test.

But something like this will check if props is a key of the object test

const test = {
  a: '1',
  b: '2',
  c: '3',
};

type KEYS = keyof typeof test;

const getType = (props: KEYS | string) => {
  let isKey = Object.keys(test).includes(props);
  const receivedType = isKey ? test[props] : '4';
}

CodePudding user response:

The first observation is that the union KEYS | string will just simplify to string. If you want to provide hints about the correct properties to pass in but still allow any string you can use KEYS | (string & {}) which will not reduce to string (looks strange, is not documented, but works)

The second part is that since test has a type and you want to index it with any string you will need to use a type assertion to get it to work. Also for testing the property you could just use the in operator:

const getType = (props: KEYS | (string & {})) => {
 const receivedType =
    props in test
      ? (test as Record<string, string>)[props]
      : '4';
}

Playground Link

  • Related