isKeyof
The isKeyof() method checks whether a key exists in an object and narrows the key type accordingly.
Interactive example
Syntax
Classic signature
typescript
function isKeyof<
GenericObject extends object,
GenericKey extends ObjectKey
>(
key: GenericKey,
obj: GenericObject
): key is keyof GenericObject & GenericKeyCurried signature
typescript
function isKeyof<
GenericObject extends object,
GenericKey extends ObjectKey
>(
obj: GenericObject
): (key: GenericKey) => key is keyof GenericObject & GenericKeyParameters
key: The key to check (string, number, or symbol).obj: The object in which to check for the key's existence.
Return value
A boolean indicating whether the key exists in the object. The return type uses a conditional type assertion to narrow the type of key when the condition is true.
See also
includes- Checks whether a substring is presentstartsWith- Checks whether a string starts with a substringendsWith- Checks whether a string ends with a substring
Sources
- TypeScript - Type Guards - Documentation on type guards
