Skip to content

Instantly share code, notes, and snippets.

@AlexZeitler
Created June 29, 2020 09:49
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 AlexZeitler/72915ae7cd8e473f74fb44b3ae262939 to your computer and use it in GitHub Desktop.
Save AlexZeitler/72915ae7cd8e473f74fb44b3ae262939 to your computer and use it in GitHub Desktop.
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