TypeScript 2.1 introduced elegant way to handle this issue.
const key: (keyof ISomeObject) = 'secondKey';
const secondValue: string = someObject[key];
We can access all object property names during compilation phase by keyof
keyword (see changelog).
You only need to replace string
variable type with keyof ISomeObject
.
Now compiler knows key
variable is allowed to contain only property names from ISomeObject
.
Full example:
interface ISomeObject {
firstKey: string;
secondKey: string;
thirdKey: number;
}
const someObject: ISomeObject = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 3
};
const key: (keyof ISomeObject) = 'secondKey';
const secondValue: string = someObject[key];
// You can mix types in interface, keyof will know which types you refer to.
const keyNumber: (keyof ISomeObject) = 'thirdKey';
const numberValue: number = someObject[keyNumber];
Live code on typescriptlang.org (set noImplicitAny
option)
Further reading with more keyof
usages.