Reputation: 3747
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
Reputation: 23515
What is happening is that at the moment of the assignation, propName
is of type "someProp" | "anotherProp"
.
Typescript does a simple thing :
obj
inside of data.someProp
? Yesobj
inside of data.anotherProp
? No -> ErrorTo 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