[英]Property does not exist on interface in React Typescript
I am pretty new to React but with some Angular attempts before.我是 React 的新手,但之前有过一些 Angular 尝试。
I was actually trying to implement a component which accepts a data model or object as parameter我实际上是在尝试实现一个接受数据模型或对象作为参数的组件
Looks like this看起来像这样
import react from 'react'
interface SmbListItem{
index:number;
primary:string;
secondary:string;
}
export default function SmbList({props}:SmbListItem){
return(
<>
</>
);
}
But its saying props does not exists on SmbListItem但是它的 saying 道具在 SmbListItem 上不存在
What I did wrong?我做错了什么?
Also requesting a suggestion on interface or types are the best option in this situation在这种情况下,还要求对接口或类型提出建议是最好的选择
import react from 'react'
interface SmbListItem{
index:number;
primary:string;
secondary:string;
}
export default function SmbList({index, primary, secondary}:SmbListItem){
return(
<>
</>
);
}
There is no such props
defined in your Interface Props
您的Interface Props
中没有定义此类props
Even if you are not using Ts
and you are sure about the props
you would destructure
your props
like this即使你不使用Ts
并且你确定你props
像这样destructure
你的props
export default function SmbList({index, primary, secondary}){
return(
<></>
);
}
For Your Second Question Have a look into Types vs Interface对于您的第二个问题,请查看类型与接口
First, You are trying to destructure
the props
parameter in the function definition, but you are not passing any props to the function.首先,您试图destructure
函数定义中的props
参数,但您没有将任何道具传递给函数。 In that case, You need to use generic type
function for that case.在这种情况下,您需要在这种情况下使用generic type
函数。
If you're new to react-typescirpt
world.如果你是react-typescirpt
世界的新手。 Then, You need to read this first:- TypeScript Docs .然后,您需要先阅读此内容:- TypeScript Docs 。
A generic type is a type that allows you to define a type or function with one or more placeholder types that can be filled in with specific types when the generic is used.泛型类型是一种允许您使用一个或多个占位符类型定义类型或函数的类型,这些占位符类型在使用泛型时可以用特定类型填充。
I found an good example for that:-我找到了一个很好的例子:-
function identity<T>(arg: T): T {
return arg;
}
let numberIdentity = identity(5); // numberIdentity is of type number
let stringIdentity = identity("hello"); // stringIdentity is of type string
Here is example with your code:-这是您的代码示例:-
export default function SmbList<T extends SmbListItem>({ props }: T) {
return <>// You code...</>;
}
The props
parameter is of a type that extends the SmbListItem
interface. props
参数属于扩展SmbListItem
接口的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.