zoukankan      html  css  js  c++  java
  • TypeScript + React 组件属性之间的依赖

    考察如下场景:

    • 一个自定义的下拉选择框有个 type 属性包含两种可能的值 "native" | "simulate"
    • typesimulate 时还希望传递一个 appearence控制其样式
    • typenative 时则不希望传递 appearence 属性

    appearence 属性是否通过 TypeScript 的类型检查依赖于 type 的值,请问组件的属性类型如何定义。

    一开始会以为这里需要借助泛型等手段来构造一个复杂类型,其实大可不必。因为后来一想不防用 Union Types 试试,实践后证实,事情其实没想的那么复杂。

    类型定义:

    type SelectProps =
      | {
          type: "native";
        }
      | {
          type: "simulate";
          appearance: "default" | "link" | "button";
        };

    使用:

    function CustomSelect(props: SelectProps) {
      return <div>...</div>;
    }
    
    function App() {
      return (
        <>
        {/* ✅ */}
          <CustomSelect type="native" />
          {/* ❌ Type '{ type: "native"; appearance: string; }' is not assignable to type 'IntrinsicAttributes & SelectProps'.
      Property 'appearance' does not exist on type 'IntrinsicAttributes & { type: "native"; }'. */}
          <CustomSelect type="native" appearance="button" />
          {/* ❌ Type '{ type: "simulate"; }' is not assignable to type 'IntrinsicAttributes & SelectProps'.
      Property 'appearance' is missing in type '{ type: "simulate"; }' but required in type '{ type: "simulate"; appearance: "default" | "link" | "button"; }'. */}
          <CustomSelect type="simulate" />
        {/* ✅ */}
          <CustomSelect type="simulate" appearance="button" />
        </>
      );
    }

    The text was updated successfully, but these errors were encountered:

    CC BY-NC-SA 署名-非商业性使用-相同方式共享
  • 相关阅读:
    CSS的未来:游戏的变革Flexbox
    2013年第8周一JAVA对象序列化及TODO标签等
    大年初七回杭州
    2013年2月20日星期三
    2013年周六加班杂记
    大家初八但杭州收拾准备开始工作
    大家初六去香山
    2013年第8周四又是低效的一天
    2013年第8周二Delphi中Union结构
    2013年第8周日元宵节
  • 原文地址:https://www.cnblogs.com/Wayou/p/14695383.html
Copyright © 2011-2022 走看看