Why can't I pass type information when drilling into props when using React and TypeScript?
P粉776412597
P粉776412597 2023-09-14 17:35:21
0
1
523

I am a long-time React user, but currently trying to learn Typescript.

In React, when you need to pass props across several levels, why don't the types defined by the top-level parent component remain in the props? It seems frustrating to have to redefine types on the parent component and all child components passing variables.

For example, I defined a State variable on the parent component and added its type, then passed it to the child component. In the props of the child component, I will get an error: Binding element 'var name' implicitly has an 'any' type. So I either need to redefine the type on the child component or export the type and import it in the child component.

Looks like a lot of extra work is needed. Did I do something wrong?

P粉776412597
P粉776412597

reply all(1)
P粉761718546

What is the relationship between status type and attribute type? There is no implicit relationship between the two, so it needs to be defined in both places.

If the component is independent, it can be used in any parent component, so it cannot get information from any specific parent state.

It's fairly common to centralize types in their own module...

// types.ts

interface User {
  id: number;
  name: string;
}

export type { User };
// Child.tsx

import type { User } from "./types";

interface ChildProps {
  user: User; // 定义属性类型
}

const Child = ({ user }: ChildProps) => {
  return <p>你好,{user.name}</p>;
}

export default Child;
// Parent.tsx

import type { User } from "./types";
import Child from "./child";

const Parent = () => {
  // 在状态中使用 User 类型
  const [user, setUser] = useState<User>({ id: 1, name: "Joe" });

  return <Child user={user} />;
};

Please note that a component's properties are part of its contract. A parent component cannot use a child component without providing a property value that satisfies the defined type.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template