reactjs 如何在React with typescript中通过父元素的props类型限制子元素的props值

rta7y2nd  于 2022-11-04  发布在  React
关注(0)|答案(2)|浏览(245)

我正在寻找任何方法来通过React with typescript中父元素的属性的类型来限制子元素的属性值。

type User = { name: string; age: number; };
const Parent = (props: User) => {
  return (
    <div>
      <Child field="name" /> // ok
      <Child field="age" /> // ok
      <Child field="firstName" /> // not ok
    </div>
  );
};

我正在找上面那种

n53p2ov0

n53p2ov01#

我喜欢Steve's approach,但这里有一个替代方案(见内联注解):

// The props for `Child`
type ChildProps<FieldNames> = {
    field: FieldNames;
};

// Define a generic type for the Child component.
type ChildType<FieldNames extends string> = (props: ChildProps<FieldNames>) => React.ReactElement;

// Define the component in terms of `string`
const Child: ChildType<string> = (props: ChildProps<string>) => {
    return /*...*/;
};

// Define a refined child that can only use `User` names for `field`
type User = { name: string; age: number };
const ThisChild: ChildType<keyof User & string> = Child;

// Use it
const Parent = (props: User) => {
    return (
        <div>
            <ThisChild field="name" /> // ok
            <ThisChild field="age" /> // ok
            <ThisChild field="firstName" /> // not ok
        </div>
    );
};

Playground示例

jckbn6z7

jckbn6z72#

在这种情况下,您将需要提供一个显式泛型。这是您正在寻找的吗?

type User = { name: string; age: number };
const Parent = (props: User) => {
  return (
    <div>
      <Child<User> field="name" /> // ok
      <Child<User> field="age" /> // ok
      <Child<User> field="firstName" /> // not ok
    </div>
  );
};

type ChildProps<T> = {
  field: keyof T;
};

const Child = <T extends unknown>(props: ChildProps<T>) => {
  return null;
};

Playground示例

相关问题