如何为对象数组指定TypeScript类型?(含报错及代码示例)
如何为对象数组指定TypeScript类型
错误原因
你定义的InitialState是单个对象的类型,但initialState是一个数组,直接将数组赋值给单个对象类型的变量,自然会报错——数组不具备单个对象的id、title、content属性。
正确写法
方法一:直接使用数组类型标注
在单个对象类型后添加[],表示这是由该类型对象组成的数组:
interface InitialState { id: string, title: string, content: string } // 用 InitialState[] 表示对象数组类型 const initialState: InitialState[] = [ {id: '1', title: 'post title', content: 'the fack content'}, {id: '1', title: 'post title', content: 'the fack content'}, ]
方法二:单独定义数组类型别名
如果需要给数组类型单独命名,可以创建类型别名:
// 先定义单个对象的类型 interface Post { id: string, title: string, content: string } // 定义数组类型别名 type InitialState = Post[]; const initialState: InitialState = [ {id: '1', title: 'post title', content: 'the fack content'}, {id: '1', title: 'post title', content: 'the fack content'}, ]
TypeScript中T[]表示由T类型元素构成的数组,只要明确标注数组类型,就能解决这个类型不匹配的问题。
内容的提问来源于stack exchange,提问作者Omor Faruk
相关产品推荐
相关产品推荐

