Skip to content

Commit 9224cd8

Browse files
committed
feat(blog): Add satisfies operator section to TypeScript tips post
1 parent f61b99b commit 9224cd8

File tree

1 file changed

+54
-0
lines changed
  • src/content/blog/typescript-tips

1 file changed

+54
-0
lines changed

src/content/blog/typescript-tips/index.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,58 @@ logLength([1, 2, 3]); // OK
7474
logLength({ length: 10 }); // OK
7575
```
7676

77+
## satisfies 操作符
78+
79+
TypeScript 4.9 引入的 `satisfies` 操作符,让你在保留精确类型推断的同时验证类型约束:
80+
81+
```typescript
82+
type Colors = 'red' | 'green' | 'blue';
83+
type RGB = [number, number, number];
84+
85+
// 使用类型注解:丢失了具体的字面量类型
86+
const palette1: Record<Colors, string | RGB> = {
87+
red: [255, 0, 0],
88+
green: '#00ff00',
89+
blue: [0, 0, 255],
90+
};
91+
palette1.red.map(x => x); // ❌ 报错:string | RGB 没有 map 方法
92+
93+
// 使用 satisfies:保留精确类型,同时验证结构
94+
const palette2 = {
95+
red: [255, 0, 0],
96+
green: '#00ff00',
97+
blue: [0, 0, 255],
98+
} satisfies Record<Colors, string | RGB>;
99+
100+
palette2.red.map(x => x); // ✅ OK,red 被推断为 [number, number, number]
101+
palette2.green.toUpperCase(); // ✅ OK,green 被推断为 string
102+
```
103+
104+
### 常见用途
105+
106+
```typescript
107+
// 1. 配置对象验证
108+
interface Config {
109+
apiUrl: string;
110+
timeout: number;
111+
retries?: number;
112+
}
113+
114+
const config = {
115+
apiUrl: 'https://api.example.com',
116+
timeout: 5000,
117+
retries: 3,
118+
} satisfies Config;
119+
120+
// 2. 确保对象键的完整性
121+
type Routes = 'home' | 'about' | 'contact';
122+
123+
const routes = {
124+
home: '/',
125+
about: '/about',
126+
contact: '/contact',
127+
} satisfies Record<Routes, string>;
128+
// 如果漏掉任何一个路由,TypeScript 会报错
129+
```
130+
77131
掌握这些技巧,能让你的 TypeScript 代码更加优雅和类型安全。

0 commit comments

Comments
 (0)