鸿蒙api9 upgrade api11问题记录

285 阅读1分钟
  • 报错:
Type 'null' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'null'.

原代码:

data: T = null

修改后代码:

data?: T

ArkTS要求所有字段在声明时或者构造函数中显式初始化。这和标准TS中的strictPropertyInitialization模式一样。 和kotlin类似,该属性需要声明为可空类型。

  • 报错:
Property 'id' has no initializer and is not definitely assigned in the constructor.

原代码:

id: number

修改后代码:

id: number = 0

和上一个问题类似,只不过这次不是可空属性,需要赋默认值。

  • 报错:
Type 'User | undefined' is not assignable to type 'User'.
  Type 'undefined' is not assignable to type 'User'.

原代码:

getUser(): User {
  return this.user
}

修改后代码:

getUser(): User | undefined {
  return this.user
}

可空属性使用时,需要增加对空属性的处理。

  • 报错:
Function lacks ending return statement and return type does not include 'undefined'.

上面报错都是和空安全有关的,这里又出来一个,以为还是和空安全相关的,但看属性赋值缺没问题。
原代码:

async updateUser(): Promise<User> {
  if(this.isLogin()) {
    let res = await Api.get().getUserInfo()
    return new Promise<User>((resolve, reject) => {
      if(res.isSuccessWithData()) {
        let user = this.user
        this.user.coinCount = res.data?.coinCount ?? 0
        this.user.level = res.data?.level ?? ''
        this.user.rank = res.data?.rank ?? ''
        this.setUser(user)
        resolve(this.user)
      } else {
        reject()
      }
    })
  }
}

原来是没有覆盖完全的返回值条件,补上else。

  • 报错:
Function return type inference is limited

原代码:

clear();

方法返回值需要加void,汗。

报错:

"for .. in" is not supported 

原代码:

for(let key in all) 

修改后代码:

let all = await this.preferences?.getAll() as Array<string>
for(let key of all)

使用of语法,并将all的类型强转为Array。