美文网首页
Flow工具类型(Utility Types)

Flow工具类型(Utility Types)

作者: vincent_z | 来源:发表于2018-01-28 11:34 被阅读0次

    工具类型(Utility Types)

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

    • $Keys<T>
    • $Values<T>
    • $ReadOnly<T>
    • $Exact<T>
    • $Diff<A, B>
    • $Rest<A, B>
    • $PropertyType<T>
    • $ElementType<T>
    • $ObjMap<T, F>
    • $TupleMap<T, F>
    • $Call<F>
    • Class<T>
    • $Supertype<T>
    • $Subtype<T>
    • Existential Type (*)

    $Keys<T>

    参考联合类型。

    // @flow
    const countries = {
      US: "United States",
      IT: "Italy",
      FR: "France"
    };
    
    type Country = $Keys<typeof countries>;
    
    const italy: Country = 'IT';
    const nope: Country = 'nope'; // 'nope' is not a Country
    

    $Values<T>

    // @flow
    type Props = {
      name: string,
      age: number,
    };
    
    // The following two types are equivalent:
    type PropValues = string | number;
    type Prop$Values = $Values<Props>;
    
    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<T>

    // @flow
    type Props = {
      name: string,
      age: number,
      // ...
    };
    
    type ReadOnlyProps = $ReadOnly<Props>;
    
    function render(props: ReadOnlyProps) {
      const {name, age} = props;  // OK to read
      props.age = 42;             // Error when writing
      // ...
    }
    

    $Exact<T>

    参考{| 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<A, B>

    // @flow
    type Props = { name: string, age: number };
    type DefaultProps = { age: number };
    type RequiredProps = $Diff<Props, DefaultProps>;
    
    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 <A,B>将会报错,即如果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<Props, DefaultProps>;
    
    function setProps(props: RequiredProps) {
      props.name;
      // ...
    }
    

    解决方案:

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

    相关文章

      网友评论

          本文标题:Flow工具类型(Utility Types)

          本文链接:https://www.haomeiwen.com/subject/nfvaaxtx.html