Typescript TS2339属性在类型上不存在-类简化 [英] Typescript TS2339 Property doesn't exist on type - Class decleration

查看:2443
本文介绍了Typescript TS2339属性在类型上不存在-类简化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Typescript

解决方案

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

  class Student {
fullName:string;
构造函数(公共名,公共MiddleInitial,公共名){
this.fullName = this.firstName + + this.middleInitial + + this.lastName;
}
}

编辑:工作小提琴


I am using exact example outlined in Typescript https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html#classes

This is exact copy I am running in 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);

}

but I get following errors

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'.

I am using typescript 2.4 and here the 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"
  ]
}

解决方案

You are declaring some public properties of your class directly in the consctructor so you should use "this" keyword

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

Edit : working fiddle

这篇关于Typescript TS2339属性在类型上不存在-类简化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆