is-typeof-property
v0.2.0
Published
Simple utility for `if (typeof object[property]) ...` type narrowing.
Downloads
5
Readme
isTypeOfProperty(object, key, type)
Simple utility for
if (typeof object[property]) ...
type narrowing.
TypeScript as of version 4.6 does not support discriminated union based on the type of properties, so the code below does not work as "expected":
let value!: {x: string; y: 'string'} | {x: number; y: 'number'};
if (typeof value.x === 'string') {
// Expecting `value.y` to be 'string', but gets 'string' | 'number'.
}
With this utility function:
import isTypeOfProperty from 'is-typeof-property';
if (isTypeOfProperty(value, 'x', 'string')) {
// Type of `value.y` is now 'string'.
}
Installation
yarn add is-typeof-property
# or
npm install is-typeof-property
License
MIT License.