Created
June 29, 2020 09:49
-
-
Save AlexZeitler/72915ae7cd8e473f74fb44b3ae262939 to your computer and use it in GitHub Desktop.
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
type Person = { | |
firstName: string | |
lastName: string | |
middleName?: string | |
} | |
const hasValue = (value: Record<string, any>, property: any): boolean => | |
Boolean(value[property]) | |
type ValueOf<T> = T[keyof T] | |
function propertyExpression<T, V extends T[keyof T]>( | |
f: (x: T) => V | |
): ValueOf<{ [K in keyof T]: T[K] extends V ? K : never }> | |
function propertyExpression(f: (x: any) => any): keyof any { | |
const p = new Proxy( | |
{}, | |
{ | |
get(target, prop) { | |
return prop | |
} | |
} | |
) | |
return f(p) | |
} | |
const person: Person = { | |
firstName: 'John', | |
lastName: 'Doe' | |
} | |
console.log( | |
hasValue( | |
person, | |
propertyExpression((p: Person) => p.middleName) | |
) | |
) | |
// const hasValue = (value: unknown): boolean => Boolean(value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment