简体   繁体   English

简单的 TypeScript 类给出了 TypeError

[英]Simple TypeScript Class gives TypeError

I want to use class Literal from file Classes.tsx in file App.tsx but TypeScript returns a TypeError even if they're in the same file.我想在文件 App.tsx 中使用文件 Classes.tsx 中的类文字,但即使它们在同一个文件中,TypeScript 也会返回 TypeError。 Works fine on typescriptlang.org/play .typescriptlang.org/play上工作正常。

// Classes.tsx
abstract class Expression {
  abstract val: boolean;
  abstract str: string;
}

class Literal extends Expression {
  val: boolean;
  constructor(value: boolean) {
    super();
    this.val = value;
  }
  get str(): string {
    return this.val ? "W" : "F";
  }
}
// App.tsx
import { Expression, Literal } from "./Classes";

let F: Literal = new Literal(false);

Error: TypeError: Cannot set property str of #<Literal> which has only a getter错误: TypeError: Cannot set property str of #<Literal> which has only a getter

Why?为什么?

There is two solutions:有两种解决方案:

  1. adding setter添加二传手
  2. change declaration to getter (from abstract str: string; to abstract get str(): string;将声明更改为 getter(从abstract str: string;abstract get str(): string;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError:不是函数打字稿类 - TypeError: is not a function typescript class 简单的 typescript 文件给出未定义导出错误 - Simple typescript file gives exports is not defined error 带有 babel、typescript 和 webpack 的简单库 - TypeError: (...) is not a function; 在 Object。<anonymous></anonymous> - Simple library with babel, typescript and webpack - TypeError: (…) is not a function; at Object.<anonymous> 打字稿中的类型错误 - TypeError in Typescript 无法导出/导入TypeScript类:“ TypeError:Messenger不是构造函数” - Unable to export/import a TypeScript class: “TypeError: Messenger is not a constructor” 从 TypeScript 调用 JavaScript 类:未捕获的 TypeError ... 不是构造函数 - Calling JavaScript class from TypeScript : Uncaught TypeError ... is not a constructor 具有可选路径参数的简单React Router提供&#39;TypeError:无法读取未定义的属性&#39;filter&#39; - Simple React Router with an Optional Path Parameter gives 'TypeError: Cannot read property 'filter' of undefined' 如何将简单的可迭代类从JavaScript重写为TypeScript? - How to rewrite the simple iterable class from JavaScript to TypeScript? 集合上的.fetch()给出TypeError - .fetch() on collection gives TypeError Picker示例给出TypeError - Picker example gives a TypeError
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM