Sea*_*azi 1 javascript types typescript flowtype
有没有办法正确键入流程或打字稿中的以下代码?:
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
Run Code Online (Sandbox Code Playgroud)
任何类型的get通用功能在哪里obj.我们可以用流检查是否obj有的方式来注释代码prop吗?
主要用例是为深层属性编写通用get函数.具有类似功能的东西_.get.我试图避免这种情况:
if (a && a.b && a.b.c && a.b.c.d === 'blah') { ... }
Run Code Online (Sandbox Code Playgroud)
如@vkurchatkin所述,我们可以使用$Keys.但我只能使用1级深度的getter函数.我们如何键入以下函数:
get<T: {}>(obj: T, prop1: $Keys<T>, prop2: /* ! */): /* ! */ { ... }
Run Code Online (Sandbox Code Playgroud)
到目前为止我写了以下内容:
type A = {
x: B
}
type B = {
y: string
}
type GetDeep<T: {}, U, V> = Helper<T, U, V, Get<T, U>, Get<U, V>>
type Helper<T, U, V, W, X> = (obj: T, a: $Keys<T>, b: $Keys<U>) => V
type Get<T, U> = (obj: T, a: $Keys<T>) => U;
// NOTE: here if I replace GetDeep<*, B, *> with GetDeep<*, *, *>
// then it wrongly type checks everything
const getDeep: GetDeep<*, B, *> = (obj, a, b) => {
return obj[a][b];
}
var va: A = {
x: {y: 'abc'}
}
getDeep(va, 'x', 'y'); // ok
getDeep(va, 'x', 'z'); // error
Run Code Online (Sandbox Code Playgroud)
它看起来像type Get<T, U> = (obj: T, a: $Keys<T>) => U,U不是价值的类型obj[a].
你可以用Flow做到这一点:
function get<T: {}>(obj: T, prop: $Keys<T>) {
return obj[prop];
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,返回的类型被推断为any.Flow目前已经$PropertyType开始工作了,所以我相信这在将来是可能的(它还没有按预期工作):
function get<T: {}, P: $Keys<T>>(obj: T, prop: P): $PropertyType<T, P> {
return obj[prop];
}
Run Code Online (Sandbox Code Playgroud)
使用此类型,您将能够深入两个级别:
function getDeep<
T: {},
P: $Keys<T>,
R: $PropertyType<T, P>,
P2: $Keys<R>
>(obj: T, a: P, b: P2): $PropertyType<R, P2> {
return obj[a][b];
}
Run Code Online (Sandbox Code Playgroud)
或者做一些可组合的东西.