Sean Shirazi Sean Shirazi - 1 year ago 117
TypeScript Question

Flowtype/Typescript general purpose get property

Is there any way to properly type check the following code in either flow or typescript?:

type A = {
x: string
type B = {
y: string
function get(obj, prop) {
return obj[prop];
const a: A = { x: 'x' }
const b: B = { y: 'y' }

get(a, 'x') // should type check
get(b, 'y') // should type check
get(a, 'y') // should NOT type check
get(b, 'x') // should NOT type check

is a general purpose function for
of any type. Can we annotate the code in a way that flow will check if

The main use case is writing a general purpose get function for deep properties. Something with similar functionality as
. I'm trying to avoid this situation:

if (a && a.b && a.b.c && a.b.c.d === 'blah') { ... }

Answer Source

You can do it with Flow:

function get<T: {}>(obj: T, prop: $Keys<T>) {
    return obj[prop];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download