[英]typescript error:2339. how can I use multiple types of object in one variable?
I'm trying to make component with vanilla js + typescript我正在尝试使用 vanilla js + typescript 制作组件
I made class "Component".我制作了 class “组件”。 the problem is "state"
问题是“状态”
interface boardState {
items: string[];
page: number;
}
interface postState {
writer: string;
content: string;
}
class Component {
$target : Element;
state: boardState | postState;
constructor() { ...}
init() { ...}
setState() { ...}
render() { ...}
}
class Board extends Component{
constructor(selector) {
super(selector);
}
init(){
this.state.items = ["title1", "title2"] ; // error
}
}
and this is class "Board" extends Component.这是 class “板”扩展组件。
I want to use different types of state.我想使用不同类型的 state。 ex) boardState, postState, pageState
例如)boardState、postState、pageState
but when i use state.items
in Board the error occurred.但是当我在 Board 中使用
state.items
时,发生了错误。
error message: TS2339: Property 'items' does not exist on type 'postState|错误消息:TS2339:类型 'postState| 上不存在属性 'items' boardState'.
板州”。
how can I fix it?我该如何解决?
Can you just overr the type in the Board
class?你能改写
Board
class 中的类型吗?
eg例如
interface boardState {
items: string[];
page: number;
}
interface postState {
writer: string;
content: string;
}
class Component {
$target : Element;
state: boardState | postState;
}
class Board extends Component{
state: boardState;
constructor() {
super();
}
init(){
this.state.items = ["title1", "title2"] ;
}
}
https://typescript-bygs7m.stackblitz.io https://typescript-bygs7m.stackblitz.io
state
can either be boardState
or postState
, not both state
可以是boardState
或postState
,不能同时是
In the case that it is postState
and you attempt to set the value of state.items
, it will not work, so TypeScript throws an error.如果它是
postState
并且您尝试设置state.items
的值,它将不起作用,因此 TypeScript 会引发错误。
that's because you only have items
in boardState
, what you need is do type narrowing
and manage the case where items doesn't exist, in the TS documentation you can see more about that https://www.typescriptlang.org/docs/handbook/2/narrowing.html那是因为您在
boardState
中只有items
,您需要进行type narrowing
并管理项目不存在的情况,在 TS 文档中您可以看到更多关于https://www.typescriptlang.org/docs/handbook /2/变窄.html
but in your case, I think is better add the member in the Board class但在你的情况下,我认为最好在董事会 class 中添加成员
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.