[英]Property 'id' does not exist on type '{} | BoardType'
I am working with Typescript in my Reactjs ( v18 ) version.我在我的 Reactjs ( v18 ) 版本中使用 Typescript 。 I have a problem below
我在下面有问题
export interface BoardType {
id: string,
columnOrder: string[] | [],
columns: string[]
}
const [board, setBoard] = useState<BoardType | {}>({});
const ABC = board.id; // Property 'id' does not exist on type '{} | BoardType'
I don't know why this error happened.我不知道为什么会发生这个错误。 Could someone explain it to me?
有人可以向我解释吗? Thanks for your support!
谢谢你的支持!
makes no sense to setBoard to an empty object.将 setBoard 设置为空的 object 是没有意义的。 Make it null...
使它成为 null...
const [board, setBoard] = useState<BoardType | null>();
const ABC = board?.id;
You are giving the initial state: {}
in useState
您在
useState
中给出初始 state: {}
BoardType
has an id but {}
does not. BoardType
有一个 id,但{}
没有。 So board
which is BoardType | {}
所以
board
是BoardType | {}
BoardType | {}
may not have one. BoardType | {}
可能没有。
You can use optional chaining and you will get undefined if board
is {}
您可以使用可选链接,如果
board
是{}
,您将得到未定义
Like this: const ABC = board?.id;
像这样:
const ABC = board?.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.