Created
August 26, 2019 11:13
-
-
Save hasparus/a96540336c1ca12992d69fdf6f07a3b0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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