Flow工具类型(Utility Types)

工具类型(Utility Types)

Flow提供了一组实用的工具类型,可用于其他类型的操作,并可用于不同的场景。

  • $Keys
  • $Values
  • $ReadOnly
  • $Exact
  • $Diff
  • $Rest
  • $PropertyType
  • $ElementType
  • $ObjMap
  • $TupleMap
  • $Call
  • Class
  • $Supertype
  • $Subtype
  • Existential Type (*)

$Keys

参考联合类型。

// @flow
const countries = {
  US: "United States",
  IT: "Italy",
  FR: "France"
};

type Country = $Keys;

const italy: Country = 'IT';
const nope: Country = 'nope'; // 'nope' is not a Country

$Values

// @flow
type Props = {
  name: string,
  age: number,
};

// The following two types are equivalent:
type PropValues = string | number;
type Prop$Values = $Values;

const name: Prop$Values = 'Jon';  // OK
const age: Prop$Values = 42;  // OK
const fn: Prop$Values = () => {};  // Error! function is not part of the union type

$ReadOnly

// @flow
type Props = {
  name: string,
  age: number,
  // ...
};

type ReadOnlyProps = $ReadOnly;

function render(props: ReadOnlyProps) {
  const {name, age} = props;  // OK to read
  props.age = 42;             // Error when writing
  // ...
}

$Exact

参考{| key: type |}

// @flow
type ExactUser = $Exact<{name: string}>;
type ExactUserShorthand = {| name: string |};

const user2 = {name: 'John Wilkes Booth'};
// These will both be satisfied because they are equivalent
(user2: ExactUser);
(user2: ExactUserShorthand);

$Diff

// @flow
type Props = { name: string, age: number };
type DefaultProps = { age: number };
type RequiredProps = $Diff;

function setProps(props: RequiredProps) {
  // ...
}

setProps({ name: 'foo' });
setProps({ name: 'foo', age: 42, baz: false }); // you can pass extra props too
setProps({ age: 42 }); // error, name is required

请注意,如果要从中删除属性的对象不具有要删除的属性,则$Diff 将会报错,即如果B具有A中不存在的键:

// @flow
type Props = { name: string, age: number };
type DefaultProps = { age: number, other: string }; // Will error due to this `other` property not being in Props.
type RequiredProps = $Diff;

function setProps(props: RequiredProps) {
  props.name;
  // ...
}

解决方案:

type A = $Diff<{}, {nope: number}>; // Error
type B = $Diff<{}, {nope: number | void}>; // OK

你可能感兴趣的:(Flow工具类型(Utility Types))