gpt4 book ai didi

reactjs - 类型 'splice' 上不存在属性 'T'

转载 作者:行者123 更新时间:2023-12-05 02:34:48 24 4
gpt4 key购买 nike

我在使用 typescript 时遇到错误 Property 'splice' does not exist on type 'T'

type Item = {
name: string,
body: string,
imgOne: string,
imgTwo: string,
}[]
// In a different file, this function is present
interface Props<T> {
className?: string;
items: T
setItems: Dispatch<SetStateAction<T>>;
children?: ReactNode
}

export const Carousel = <T extends object>({className, items, setItems, children}: Props<T>) => {
console.log(items.splice(0,2));

return <div />
}

// I am calling this function in a 3rd file.
export const HomeCarousel: FC = () => {
const {Root} = useStyles();
const classes = useStylesClasses();

const [items, setItems] = useState<Item[]>([
{
name: "Naruto1",
body: "Dive into the world of shinobi to witness one of the greatest tales",
imgOne: "/two.svg",
imgTwo: "/one.svg",
},
{
name: "Naruto2",
body: "Dive into the world of shinobi to witness one of the greatest tales",
imgOne: "/two.svg",
imgTwo: "/one.svg",
},
{
name: "Naruto3",
body: "Dive into the world of shinobi to witness one of the greatest tales",
imgOne: "/two.svg",
imgTwo: "/one.svg",
},
]);


return (
<Root>
<Carousel<Item[]> setItems={setItems} items={items}>
{items.map((item, index)=> {
return <CarouselItem name={item.name}/>
})}
</Carousel>
</Root>
)
}

拼接函数不起作用,现在一方面它是有意义的,因为类型 Item 中没有拼接,但它不应该默认工作吗,因为它是一个数组?

感谢任何帮助!

最佳答案

尝试替换 T extends objectT extends Array<unknown> .

这样你就可以声明 T (在您的情况下 items: T )将始终是某种数组而不是通用对象。因此 TS 会知道 T会有.splice()方法,因为它“继承”自 Array .

更新如果那不是一个选项 - 你必须检查 Tobject实际上是一个数组。像这样:

if (Array.isArray(items)) {
console.log(items.splice(0, 2));
} else {
throw "Expected items to be an array"
}

或者,如果您想使用 .splice()将来在任何对象上无需检查它,您可以使用它:T extends { splice: Array<never>["splice"] } .它将确保所有类型的对象都需要您定义自己的 .splice() 实现。与 Array.splice() 兼容的方法方法。

关于reactjs - 类型 'splice' 上不存在属性 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70706536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com