首页 > 其他分享 >[Typescript 4.9] TypeScript 4.9: satisfies operator

[Typescript 4.9] TypeScript 4.9: satisfies operator

时间:2023-01-19 04:55:05浏览次数:54  
标签:TypeScript 4.9 number value RGB green operator type red

Previously, we have problem for such code:

type RGB = readonly [red: number, green: number, blue: number];
type Color = { value: RGB | string };

const myColor: Color = { value :'red' };

myColor.value.toUpperCase() // Property 'toUpperCase' does not exist on type 'string | RGB'.

 

With TS 4.9, it works

type RGB = readonly [red: number, green: number, blue: number];
type Color = { value: RGB | string };

const myColor = { value :'red' } satisfies Color;

myColor.value.toUpperCase() // works, now myColor.value is narrowing down to string type

 

Working with as const

type RGB = readonly [red: number, green: number, blue: number];
type Color = RGB | string;

const palette = {
    red: [255, 0, 0],
    green: "#00ff00",
    blue: [1,2,3],
} satisfies Record<string, Color>;

console.log(palette.green); // green is a string type

const constantPalette = {
    red: [255, 0, 0],
    green: "#00ff00",
    blue: [1,2,3],
} as const satisfies Record<string, Color>;

console.log(constantPalette.green);  // green is "#00ff00"

 

Blog

标签:TypeScript,4.9,number,value,RGB,green,operator,type,red
From: https://www.cnblogs.com/Answer1215/p/17060995.html

相关文章

  • 【TypeScript】学习笔记
    一.环境搭建安装Node.jsnpmi-gtypescript创建ts文件test.ts,编译:tsctest.ts二.基本类型1.类型声明语法:let变量:类型;let变量:类型=值;functionfn(参数:类型,参数:......
  • typescript中特殊符号(?/!)用法
    1.属性或参数中使用 ?:表示该属性或参数为可选项2. 属性或参数中使用 !:表示强制解析(告诉typescript编译器,这里一定有值),常用于vue-decorator中的@Prop3.变量后使用 !:表......
  • K8S Operator的开发与使用
    从应用角度考虑,为什么会出现如此多的Operator场景,为什么很多中间件和厂商都会提供基于Operator的部署方案,他的价值是什么?随着时代的发展,企业应用部署环境从传统的物理机->......
  • typescript封装LocalStorage并支持过期时间
    思考在我们使用​​cookie​​​的时候是可以设置有效期的,但是​​localStorage​​​本身是没有该机制的,只能人为的手动删除,否则会一直存放在浏览器当中,可不可以跟cookie一......
  • 学习TypeScript 加餐环节
    ​​object​​​、​​Object​​​ 以及​​{}这三个类型大家可能不太理解​​1.​​Object​​ ​​Object​​​类型是所有​​Object​​类的实例的类型。由以下......
  • Prometheus Operator配置Alertmanager告警
    1、管理Alertmanagerconfiguration1.1方式一,使用存储在Kubernetessecret中的本地Alertmanager配置文件1、编写alertmanager配置alertmanager.yamlroute:group_by......
  • [Typescript] Represent Generics at the Lowest Level
      Therearetwosolutionstothischallenge,bothwithdifferentwaysofrepresentingthegeneric.Solution1:Thefirstoptionisusing TConfig whichex......
  • PowerISO v4.9
    SupportWindows7taskbarprogressbar.SupportISZfile. ImproveUDFfilesupport. Someminorbugfixesandenhancements. 下载:​​​http://www.iso-file.ne......
  • [Typescript] Use Generics in a Reduce Function
    Seethiscode:constarray=[{name:'John',},{name:'Steve',},];constobj=array.reduce((accum,item)=>{accum[item.name]=item......
  • [Typescript] Generics in Type Arguments
    Herewehavea Component classthatcanbepassedin TProps.Insideoftheconstructoritassigns props to this,andprovidesa getProps methodthatca......