代码之家  ›  专栏  ›  技术社区  ›  rony l

在typescript中强制执行子组件的属性类型

  •  3
  • rony l  · 技术社区  · 2 年前

    我正在尝试在子组件中强制执行属性的类型。 由于以下原因,我预计以下代码不会编译 Child name 内部未正确键入属性 Parent 在应用程序中,但它不显示编译器警告。

    如果我有一个 <Parent<"a">> 它不允许孩子的道具名称不等于“a”?

    type ChildProps<T> = {
      name: T;
    };
    
    type parentProps<T extends string> = {
      children: React.ReactElement<ChildProps<T>>;
    };
    
    function Parent<T extends string>({ children }: parentProps<T>) {
      return <div>{children}</div>;
    }
    
    function Child({ name }: ChildProps<"b">) {
      return <div>{name}</div>;
    }
    
    function App() {
      return (
        <Parent<"a">>
          <Child name="b" />
        </Parent>
      );
    }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   adsy    2 年前

    你不能!这也是TS面临的令人沮丧的公开问题之一。请参阅 this issue.