Sean Shirazi Sean Shirazi - 3 months ago 21
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


Where
get
is a general purpose function for
obj
of any type. Can we annotate the code in a way that flow will check if
obj
has
prop
?

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

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

Answer

You can do it with Flow:

function get<T: {}>(obj: T, prop: $Keys<T>) {
    return obj[prop];
}
Comments