[Typescript 4.9] TypeScript 4.9: satisfies operator
typescript Operator 4.9
2023-09-14 09:00:42 时间
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"
相关文章
- [Typescript] Extracting Members of a Discriminated union - Extract<T, U>
- [Typescript] Function scope in typescript
- [Typescript] TypeScript module Augmentation
- [Typescript] Making TypeScript Stick - 5 - Extends
- [Typescript] Definite assignment operator
- [Typescript] Type Guard: is & assert
- [Typescript] Key remapping in mapped types by using `as` keyword V4.2
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- [Typescript] Extend Functionality of a TypeScript Class with Decorators
- [TypeScript] Typescript Interfaces vs Aliases Union & Intersection Types
- [TypeScript] What's New in TypeScript 1.4
- [Typescript 4.9] Satisfies operator
- [Typescript] 96. Hard - Optional Keys
- [Typescript] 43. Medium - Percentage Parser
- [Typescript] Tips: Use 'in' operator to transform a union to another union(watched)
- [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
- [Typescript] Simplify iteration of custom data structures in TypeScript with iterators (backwards iteration with for ... of.. loop)
- [Typescript] Make TypeScript Class Usage Safer with Strict Property Initialization
- [VueJS + Typescript] Decouple Dependencies Using IoC Containers in Vue with TypeScript and InversifyJS
- [TS] Implement a doubly linked list in TypeScript
- typescript入门笔记自用2(类&函数)