😎
tsの配列に対して、条件に応じてpushしたい
元ツイ
1. 普通にifで分岐
type Apartment = {
metersToStation: number;
ageOfBuilding: number;
options: string[];
};
const apartment: Apartment = {
metersToStation: 400,
ageOfBuilding: 5,
options: ["ShoeLocker", "AutoLock"],
};
const salesPoints1: string[] = [];
if (apartment.metersToStation < 1000) {
salesPoints1.push('駅近');
}
if (apartment.ageOfBuilding < 5) {
salesPoints1.push('築浅');
}
if (apartment.options.includes('AutoLock')) {
salesPoints1.push('セキュリティ充実');
}
2. 短絡評価とfilterと型ガード
type Apartment = {
metersToStation: number;
ageOfBuilding: number;
options: string[];
};
const apartment: Apartment = {
metersToStation: 400,
ageOfBuilding: 5,
options: ["ShoeLocker", "AutoLock"],
};
const salesPoints2: string[] = [
apartment.metersToStation < 1000 && "駅近",
apartment.metersToStation < 5 && "築浅",
apartment.options.includes("AutoLock") && "セキュリティ充実",
].filter<string>((point): point is string => typeof point === "string");
3. ジェネレーター
type Apartment = {
metersToStation: number;
ageOfBuilding: number;
options: string[];
};
const apartment: Apartment = {
metersToStation: 400,
ageOfBuilding: 5,
options: ["ShoeLocker", "AutoLock"],
};
function* makeSalesPoint(apartment: Apartment) {
if (apartment.metersToStation < 1000) yield "駅近";
if (apartment.ageOfBuilding < 5) yield "築浅";
if (apartment.options.includes("AutoLock")) yield "セキュリティ充実";
}
const salesPoints3: string[] = [...makeSalesPoint(apartment)];
全体コード
Discussion