How do I let TypeScript know that a function validates that an item contains a given key?
e.g.:
function doesItemHaveKey(item: any, key: string): boolean {
return typeof item === 'object' && item !== null && typeof item[key] !== 'undefined';
}
interface testInterface {
optional?: string;
some: string;
}
let testObj: testInterface = {
some: 'value'
};
if (doesItemHaveKey(testObj, 'some')) {
// Do something with testObj.some
// TypeScript throws errors because `testObj.some` could be undefined
}
Things I've tried:
if (doesItemHaveKey(testObj, 'some') && typeof testObj.some !== 'undefined') {
// This works, but duplicates the typeof check
}
function doesItemHaveKey(item: any, key: string): key is keyof item
/**
* A type predicate's type must be assignable to its parameter's type.
* Type 'string | number | symbol' is not assignable to type 'string'.
* Type 'number' is not assignable to type 'string'.
**/
someotherwisesomeis not types as possibly undefinedtestObj.somedoesn't give a type error in that code.