简体   繁体   中英

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? I'm looking to use the $NonMaybeType<T> utility to help me here.

In typescript this would be:

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.

Playground

Flow provides an $ObjMap utility type which you can use to map over the values and turn them into non-nullables via $NonMaybeType .

type MyObject = $ReadOnly<{
  foo: ?number,
  bar: ?number,
  baz: ?number,
}>;

type NonMaybeValueType = <V>(V) => $NonMaybeType<V>;
type MyNonNullValuesObject = $ObjMap<MyObject, NonMaybeValueType>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM