前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >typescript 中的 const assertions

typescript 中的 const assertions

作者头像
老麦
发布2022-12-24 09:37:52
1.1K0
发布2022-12-24 09:37:52
举报
文章被收录于专栏:Go与云原生Go与云原生

const assertions - TypeScript 3.4

代码语言:javascript
复制
// vue3

const dnsProviders = {
    "aliyun.com": "alidns",
    "tencent.com": "dnspod"
}

let data = reactive({
    rootDomain: "aliyun.com" as const
})

let dnsProvider = computed(
    () => {
        return dnsProviders[data.rootDomain]
    }
)

这个时候会, 提示 7053 错误, data.rootDomain 具有 any type, 不能被用作 key。

解决这个问题使用, 需要使用 typescript 中 const assertion 类型推断。

const assertion 类型推断。

  1. 字面量类型推断: 其类型为字面值类型。
    1. 例如这里的 hello 的类型是 hello 不是 string
    2. n 的类型是 1 不是 number
代码语言:javascript
复制
let x = "hello" as const  // type "hello"
let n = 1 as const  // type 1
  1. object 得到的是一个只读属性
代码语言:javascript
复制
let z = { text: "hello" } as const;  // // Type '{ readonly text: "hello" }'
  1. 数组 array 得到一个 只读元组 (tuple)
代码语言:javascript
复制
let y = [10, 20] as const; // Type 'readonly [10, 20]'

注意事项

  1. const 推断只能用于 简单字面表达式, 即 string, number, boolean, array, object
代码语言:javascript
复制
// 错误! 
let a = (Math.random() < 0.5 ? 0 : 1) as const;
let b = (60 * 60 * 1000) as const;

// 可行!
let c = Math.random() < 0.5 ? (0 as const) : (1 as const);
let d = 3_600_000 as const;
  1. const 上下文执行的时候, 并不会立即将 一个可变表达式 转换成 完全不可变的 状态(readonly)
    1. foo 的属性不能进行完全替换
    2. 但是 foo 的属性 content 的值是 arr 依旧可以进行数据操作, 没有成为 readonly
代码语言:javascript
复制
let arr = [1, 2, 3, 4];
let foo = {
  name: "foo",
  contents: arr,
} as const;

// foo 的属性不能进行完全替换
foo.name = "bar"; // error!
foo.contents = []; // error!

// 但是 foo 的属性 content 的值是 arr 依旧可以进行数据操作, 没有成为 readonly
foo.contents.push(5); // ...works!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 熊猫云原生Go 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • const assertion 类型推断。
  • 注意事项
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档