Created
November 8, 2017 22:44
-
-
Save niieani/e4ff86255853c429f074f7c8a742b706 to your computer and use it in GitHub Desktop.
HasProperty TypeScript utility for checking whether an object has a property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// actual type: | |
type HasProperty< | |
T, | |
Property, | |
MappedT = AllDefinedAsTrue<T> & AllUndefinedAsFalse & Padding, | |
> = MappedT[keyof MappedT & Property]; | |
// usage: | |
type TrueExample = HasProperty<{abc: number}, 'abc'>; | |
type TrueExample2 = HasProperty<{abc: number, def: number}, 'def'>; | |
type FalseExample = HasProperty<{}, 'abc'>; | |
type FalseExample2 = HasProperty<{xyz: number}, 'abc'>; | |
type TrueExample3 = HasProperty<Function, 'apply'>; | |
// tests: | |
const ex1: TrueExample = '1'; | |
const ex2: TrueExample2 = '1'; | |
const ex3: FalseExample = '0'; | |
const ex4: FalseExample2 = '0'; | |
const ex5: TrueExample3 = '1'; | |
// helpers: | |
type AllDefinedAsTrue<T> = { | |
[P in keyof T]: '1'; | |
}; | |
type AllUndefinedAsFalse = { | |
[any: number]: '0'; | |
}; | |
// "padding" is needed, | |
// otherwise objects with one or zero props return 'any' | |
// for some reason | |
type Padding = { | |
'____________': '0'; | |
'_____________': '0'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment