打字稿改变变量值类型

时间:2021-06-22 10:46:16

标签: typescript

好吧,最近我将文件从 index.js 更改为 index.ts,这是我的问题的示例

let response = "none"
let condition = true

if(condition){
 response = {id: 123 , data: []}
}

console.log(response)

但它给了我一个语法错误说 {id: 123 , data: []} is not assignable to type string 这有点令人沮丧,因为我有超过 5000 行代码,而且我不想更改所有变量

2 个答案:

答案 0 :(得分:0)

为了使 typescript 有用,您需要实际键入属性和方法。

在您的示例中,response 变量可以是:

  • 一个“无”字符串
  • 具有 ID 和数据数组的对象

让我们告诉打字稿:

type ResponseObject = { id: number, data: any[] }

let response: "none" | ResponseObject = "none"
let condition = true

if(condition){
 // No errors here, because typescript now knows that this data type is ok
 response = {id: 123 , data: []}
}

console.log(response)

答案 1 :(得分:-2)

使用 any 类型

let response : any = "none"

但是你会失去建议的好处

否则你也可以这样做

let response : (string | {id: Number , data: Array<any>} }= "none"

你会得到一些关于这些类型的打字稿建议。