When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes
function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of using includes
to determine if a key of arbitrary string
type exists in an array with a known type?
Let's consider the following code snippet:
type CONFIG_MODEL = {
URL: string;
Protocol: string;
Port: number;
Encrypted: boolean;
}
const ALLOWED_KEYS: (keyof CONFIG_MODEL)[] = ['URL', 'Protocol'];
function setup(configs: { [key: string]: string }) {
Object.keys(configs).forEach(configKey => {
if (ALLOWED_KEYS.includes(configKey)) {
// do something
}
})
}
It turns out that TypeScript throws an error when trying to use includes
, with the message:
Argument of type 'string' is not assignable to parameter of type 'keyof CONFIG_MODEL'
Any insights or suggestions would be greatly appreciated!