[英]Cast Flow/TypeScript JavaScript object value types to non-nullable
I have the following type我有以下类型
type MyObject = $ReadOnly<{
foo: ?number,
bar: ?number,
baz: ?number,
}>;
and I want to convert all the values to non-nullable, eg;我想将所有值转换为不可为空的,例如;
type MyNonNullValuesObject = $ReadOnly<{
foo: number,
bar: number,
baz: number,
}>;
What's a good way to do so in Flow without repeating all the keys?在不重复所有键的情况下,在 Flow 中这样做的好方法是什么? I'm looking to use the
$NonMaybeType<T>
utility to help me here.我希望在这里使用
$NonMaybeType<T>
实用程序来帮助我。
In typescript this would be:在 typescript 中,这将是:
type MyObject = Readonly<{
foo: number | null,
bar: number | null,
baz: number | null,
}>;
type NonNullableObject<T> = { [K in keyof T]: NonNullable<T[K]> };
type MyNonNullableObject = NonNullableObject<MyObject>;
Mapped type using NonNullable utility.使用NonNullable实用程序映射类型。
Flow provides an $ObjMap
utility type which you can use to map over the values and turn them into non-nullables via $NonMaybeType
. Flow 提供了一个
$ObjMap
实用程序类型,您可以将其用于 map 的值,并通过$NonMaybeType
将它们转换为不可为空的值。
type MyObject = $ReadOnly<{
foo: ?number,
bar: ?number,
baz: ?number,
}>;
type NonMaybeValueType = <V>(V) => $NonMaybeType<V>;
type MyNonNullValuesObject = $ObjMap<MyObject, NonMaybeValueType>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.