Is there a way in TypeScript to indicate that a function is validating the presence of a specific key in an object?
For example:
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')) {
// Perform actions based on the existence of testObj.some
// TypeScript may flag errors if 'testObj.some' is potentially undefined
}
Attempts that have been made:
if (doesItemHaveKey(testObj, 'some') && typeof testObj.some !== 'undefined') {
// This solution works but it 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'.
**/