Typescript:读取和嵌套包含union值的接口时出错

Typescript:读取和嵌套包含union值的接口时出错,typescript,Typescript,问题 我嵌套了一个接口,该接口包含类型为union的值,以便在单独的文件中管理许多设置 将值初始化为const时没有问题,但读取值时出现问题 TS2339: Property 'rows' does not exist on type 'Grid | Waterfall'. Property 'rows' does not exist on type 'Waterfall'. 有没有避免错误的方法? 我刚刚开始使用类型脚本,所以在这种情况下我不知道如何解决类型脚本。 请帮我认识一个人 打字脚本

问题

我嵌套了一个接口,该接口包含类型为union的值,以便在单独的文件中管理许多设置

将值初始化为const时没有问题,但读取值时出现问题

TS2339: Property 'rows' does not exist on type 'Grid | Waterfall'.
Property 'rows' does not exist on type 'Waterfall'.
有没有避免错误的方法? 我刚刚开始使用类型脚本,所以在这种情况下我不知道如何解决类型脚本。 请帮我认识一个人

打字脚本版本:2.6.1

代码

interface Grid {
  rows: number;
  columns: number;
}
interface Waterfall {
  moreButton: boolean;
  forceSquare: boolean;
}
interface View {
  viewType: Grid | Waterfall;
  postType: string;
  mainColor: string;
}
const view: View = {
  viewType: {
    rows: 3,
    columns: 5
  },
  postType: 'image, video',
  mainColor: 'blue',
};

console.log(view.viewType.rows);

这是一个很好的警告;它告诉您,
view.viewType.rows
可能不存在。在编译器允许您使用它之前,您必须说服编译器它确实存在。这里有一个方法:

if ('rows' in view.viewType) {
  // view.viewType is now known to be Grid
  console.log(view.viewType.rows); // okay
  console.log(view.viewType.columns); // also works
}

这有意义吗?希望有帮助。祝你好运

如果您的
viewType
可以有行和列,或者有更多的按钮和forceSquare,那么它有点违背了静态键入的目的。我认为问题在于如何使用
viewType:Grid |瀑布它应该是一个或另一个。哦,谢谢你,我在某处找到了答案,如果我写一些类似于
if(view.viewType.rows)
的东西,它就会起作用。但它没有起作用。但是你的答案很有效。