Skip to content

Commit 2682350

Browse files
committed
add utility type and mapped type example code
1 parent c7febf2 commit 2682350

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

example/10_utility-types.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
interface Product {
2+
id: number;
3+
name: string;
4+
price: number;
5+
brand: string;
6+
stock: number;
7+
}
8+
9+
let products: Product[] = [
10+
{ id: 1, name: '참치김밥', price: 3000, brand: '김가네', stock: 3 },
11+
];
12+
13+
function displayProduct(productInfo: { id: 1; name: '참치김밥'; price: 3000 }) {
14+
// ...
15+
}
16+
17+
// #1 - Partial
18+
type Subset<T> = {
19+
[K in keyof T]?: T[K];
20+
};
21+
22+
const productDetail: Product = {
23+
id: 1,
24+
};
25+
26+
// #2 - Pick
27+
type PickFewThings<T, K extends keyof T> = {
28+
[P in K]: T[P];
29+
}
30+
31+
const productName: PickFewThings<Product, 'name'> = {
32+
33+
}
34+
const productNameWithPrice: PickFewThings<Product, 'name' | 'price'> = {
35+
36+
}

example/11_mapped-types.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// mapped types
2+
type Heroes = 'Hulk' | 'Thor' | 'Capt';
3+
type HeroAges = { [K in Heroes]: number };
4+
const ages: HeroAges = {
5+
Hulk: 'a', // hulk's age must be number
6+
};

0 commit comments

Comments
 (0)