admin管理员组

文章数量:1567260

TypeScript 语法文章:

【TypeScript】TS入门到实战(详解)_ts 使用 js-CSDN博客

【TypeScript】TS入门到实战(详解:高级类型)-CSDN博客

  • 相关报错:Property 'name' has no initializer and is not definitely assigned in the constructor

  • 翻译一下:属性'name'没有初始化,也没有在构造函数中明确赋值
  • 报错原因:在Typescript 2.7 release版本出来后,设置了一个新的编译器选项strictPropertyInitialization。当本选项 strictPropertyInitialization:true 的时候,编译器会确保一个class类中所有的属性和方法都已经初始化,如果没有,那么在属性构建的过程中就会抛出错误。
  • 解决:

        - 1、方法一(不太推荐)设置strictPropertyInitialization: false

{
  "compilerOptions": {
    "strictPropertyInitialization": false
  }
}

有点违背 TypeScript 设置为true的初衷

        - 2、方法二:针对属性,我们使用constructor构造函数初始化(推荐)

针对泛型类: (类型不确定,无法直接赋值)

class GenericNumber<NumType> {
    defaultValue: NumType
    
    constructor(defaultValue: NumType) { // 创造构造函数
        this.defaultValue = defaultValue
    }
}

(后续创造实例时,注意传参)

如果是普通的class类,也能直接对属性赋初始值:(类型确定)

class GenericNumber<string> {
    defaultValue: string = ''
}

        - 3、方法三:针对属性和方法都能使用 利用 ?  (推荐)

class GenericNumber<NumType> {
    defaultValue?: NumType
    add?: ( x: NumType, y: NumType ) => NumType
}

 但是需要注意的是,由于在泛型类中我们无法确定具体的类型,所有定义方法时是无法初始化一个方法的,所以在定义该类的实例使用方法之前需要初始化方法之后才能调用。

class GenericNumber<NumType> {
    add?: ( x: NumType, y: NumType ) => NumType
}
const myNum = new GenericNumber<number>() // 类似于泛型接口,在创建 class 实例时,在类名后面通过 <类型> 来指定明确的类型。

// 初始化方法
myNum.add = function(a, b) {
    return a + b
}
// 调用方法
const value = myNum.add(1, 2)
console.log(value)

本文标签: 报错Propertytypescriptconstructorassigned