Typescript TS2339属性在类型上不存在 - 类去除

时间:2017-07-25 08:07:07

标签: javascript class typescript types

我使用了Typescript https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#classes

中概述的确切示例

这是我在app.ts中运行的精确副本

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}



window.onload = () => {

    function greeter(person: Person) {
        return "Hello, " + person.firstName + " " + person.lastName;
    }

    var user = new Student("Jane", "M.", "User");

    document.body.innerHTML = greeter(user);

}

但我得到以下错误

ERROR in ./src/app.ts
(3,14): error TS2339: Property 'firstName' does not exist on type 'Student'.

ERROR in ./src/app.ts
(4,14): error TS2339: Property 'middleInitial' does not exist on type 'Student'.

ERROR in ./src/app.ts
(5,14): error TS2339: Property 'lastName' does not exist on type 'Student'.

ERROR in ./src/app.ts
(6,14): error TS2339: Property 'fullName' does not exist on type 'Student'.

我正在使用typescript 2.4和tsconfig

{
  "compilerOptions": {
    "module": "es2015",
    "target": "es6",
    "sourceMap": true,
    "jsx": "react",
    "lib": [
      "es6",
      "scripthost",
      "dom"
    ],
    "rootDir": ".",
    "moduleResolution": "node"
  },
  "files": [
    "node_modules/@types/react-dom/index.d.ts",
    "node_modules/@types/react/index.d.ts",
    "typings/file-loader.d.ts"
    ],
  "exclude": [
    "node_modules/@types/whatwg-fetch",
    "node_modules/@types/whatwg-streams",
    "node_modules"
  ]
}

enter image description here

2 个答案:

答案 0 :(得分:0)

您是在构造函数中直接声明您的类的一些公共属性,因此您应该使用"this"关键字

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = this.firstName + " " + this.middleInitial + " " + this.lastName;
    }
}

修改:working fiddle

答案 1 :(得分:-3)

这似乎工作正常吗?

var Student = (function() {
  function Student(firstName, middleInitial, lastName) {
    this.firstName = firstName;
    this.middleInitial = middleInitial;
    this.lastName = lastName;
    this.fullName = firstName + " " + middleInitial + " " + lastName;
  }
  return Student;
}());

function greeter(person) {
  return "Hello, " + person.firstName + " " + person.lastName;
}
var user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
<!-- TYPESCRIPT
var Student = (function () {
    function Student(firstName, middleInitial, lastName) {
        this.firstName = firstName;
        this.middleInitial = middleInitial;
        this.lastName = lastName;
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
    return Student;
}());
function greeter(person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}
var user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
-->