Skip to content

Instantly share code, notes, and snippets.

@niieani
Created November 8, 2017 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niieani/e4ff86255853c429f074f7c8a742b706 to your computer and use it in GitHub Desktop.
Save niieani/e4ff86255853c429f074f7c8a742b706 to your computer and use it in GitHub Desktop.
HasProperty TypeScript utility for checking whether an object has a property
// 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