WebLog

tsの配列に対して、条件に応じてpushしたい

2023/03/14 11:56

元ツイ

1. 普通に if で分岐

1type Apartment = {
2 metersToStation: number;
3 ageOfBuilding: number;
4 options: string[];
5};
6
7const apartment: Apartment = {
8 metersToStation: 400,
9 ageOfBuilding: 5,
10 options: ["ShoeLocker", "AutoLock"],
11};
12
13const salesPoints1: string[] = [];
14if (apartment.metersToStation < 1000) {
15 salesPoints1.push("駅近");
16}
17if (apartment.ageOfBuilding < 5) {
18 salesPoints1.push("築浅");
19}
20if (apartment.options.includes("AutoLock")) {
21 salesPoints1.push("セキュリティ充実");
22}

2. 短絡評価と filter と型ガード

1type Apartment = {
2 metersToStation: number;
3 ageOfBuilding: number;
4 options: string[];
5};
6
7const apartment: Apartment = {
8 metersToStation: 400,
9 ageOfBuilding: 5,
10 options: ["ShoeLocker", "AutoLock"],
11};
12
13const salesPoints2: string[] = [
14 apartment.metersToStation < 1000 && "駅近",
15 apartment.metersToStation < 5 && "築浅",
16 apartment.options.includes("AutoLock") && "セキュリティ充実",
17].filter<string>((point): point is string => typeof point === "string");

3. ジェネレーター

1type Apartment = {
2 metersToStation: number;
3 ageOfBuilding: number;
4 options: string[];
5};
6
7const apartment: Apartment = {
8 metersToStation: 400,
9 ageOfBuilding: 5,
10 options: ["ShoeLocker", "AutoLock"],
11};
12
13function* makeSalesPoint(apartment: Apartment) {
14 if (apartment.metersToStation < 1000) yield "駅近";
15 if (apartment.ageOfBuilding < 5) yield "築浅";
16 if (apartment.options.includes("AutoLock")) yield "セキュリティ充実";
17}
18const salesPoints3: string[] = [...makeSalesPoint(apartment)];

全体コード

TypeScript: TS Playground - An online editor for exploring TypeScript and JavaScript
TypeScript: TS Playground - An online editor for exploring TypeScript and JavaScript

TypeScript: TS Playground - An online editor for exploring TypeScript and JavaScript

The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.

最新の投稿