ChruS
ChruS

Reputation: 3747

KeysOfType and exact type of property

I'm using KeysOfType from https://stackoverflow.com/a/49752227:

type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T];

With these interfaces

interface SomeInterface {
  a: number;
  b: string;
}

interface AnotherInterface {
  a: number;
  b: string;
  c: number;
  d: string;
}

interface DataInterface {
  someProp: SomeInterface;
  anotherProp: AnotherInterface;
  ...
}

If I use it like showed below, I get error

Type 'SomeInterface' is not assignable to type 'SomeInterface & AnotherInterface '.
Type 'SomeInterface ' is missing the following properties from type 'AnotherInterface ': c, d

  const setProperty = (numberValue: number, stringValue: string, propName: KeysOfType<DataInterface, SomeInterface>) => {
    const obj: SomeInterface = {
        a: numberValue,
        b: stringValue
    };

    data[propName] = obj; // data is DataInterface
  }

How can I get property keys of DataInterface that are exactly have type of SomeInterface?

Upvotes: 1

Views: 90

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23515

What is happening is that at the moment of the assignation, propName is of type "someProp" | "anotherProp".

Typescript does a simple thing :

  • Can I put obj inside of data.someProp ? Yes
  • Can I put obj inside of data.anotherProp ? No -> Error

To show you that this is true, look at the following playground : Playground

Having the following code works :

  if (propName === 'someProp') {
    data[propName] = obj;
  }

Upvotes: 1

Related Questions