ts中的类型断言

130 阅读1分钟

首先看以下代码:

const req = {
  url: 'https://example.com',
  method: 'GET'
}

type reqTranlate = {
  url: 'https://example.com'
  method: 'GET'
}

function f4(params: reqTranlate): void {}

f4(req)

以上代码在 ts 中肯定会提示有错误,因为在函数f4的参数中给params的类型是reqTranlate,但是在这种情况下,req.urlreq.method都会被默认推断为string类型,而reqTranlate中的urlmethod的类型分别是https://example.comGET并不是string,所以会提示错误。

想要解决上面的问题可以有两种方式。

  • 方法1

在定义对象req的时候,属性后面都加上类型断言

const req = {
  url: 'https://example.com' as 'https://example.com',
  method: 'GET' as 'GET'
}

这样就能保证类型一致了。

  • 方法2

给对象加一个as const的后缀。

const req = {
  url: 'https://example.com',
  method: 'GET'
} as const

官网的描述是:

--- You can use as const to convert the entire object to be type literals.

通过一系列的测试,as const的作用应该是对对象中的每一个属性都根据属性的值的字面量进行类型断言,大概就是下面这样:

{key:value:type}
{url: 'https://example.com':'https://example.com', method: 'GET' : 'GET'}

通过给req设置as const后缀,req.url以及req.method的类型都根据他们的字面量被分别设置为了https://example.comGET,与reqTranlate中各属性的类型保持一致,一次也就不会报错了。

添加了 as const 的对象,它的属性就变成了只读的,不可再修改了!

对象req仍然是一个对象,而不是一种类型,as const的作用是给req中的每一个属性添加字面量的类型断言!