Skip to content

Instantly share code, notes, and snippets.

@hasparus
Created August 26, 2019 11:13
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 hasparus/a96540336c1ca12992d69fdf6f07a3b0 to your computer and use it in GitHub Desktop.
Save hasparus/a96540336c1ca12992d69fdf6f07a3b0 to your computer and use it in GitHub Desktop.
function hasKey<T extends object, K extends string>(x: T, key: K): x is T & { [_ in K]: unknown } {
return key in x;
}
type TypeOfs = {
string: string;
number: number;
object: object;
};
function hasShapeFlat<T extends object, S extends Record<string, keyof TypeOfs>>(
x: T,
shape: S
): x is T & { [P in keyof S]: TypeOfs[S[P]] } {
return Object.entries(x).every(([key, val]) => typeof val === shape[key]);
}
const x: object = {};
if (hasKey(x, 'a')) {
const { a } = x;
}
if (hasShapeFlat(x, { a: 'string', b: 'number' })) {
const b = x.b * 2;
const a = x.a.startsWith('a');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment