2023/06/10 ~ 2023/06/16 のもくもく日記
もくもく 前回までは
2023/06/03 ~ 2023/06/09 のもくもく日記 をご覧ください。
途中経過
その1
TypeScript でenum
の代替手段として紹介されているオブジェクトリテラル、const
, type
の定義で一緒の名前使えることにビビったw
const Position = {
Top: 0,
Right: 1,
Bottom: 2,
Left: 3,
} as const;
type Position = typeof Position[keyof typeof Position];
※引用元
その2
TypeScript のinterface
の型判定、型ガード関数を使う感じらしいのだけど、ついつい忘れてしまう……。
interface Student {
name: string;
grade: number;
}
// Student型かを判定する型ガード関数
function isStudent(value: unknown): value is Student {
// 値がオブジェクトであるかの判定
if (typeof value !== "object" || value === null) {
return false;
}
const { name, grade } = value as Record<keyof Student, unknown>;
// nameプロパティーが文字列型かを判定
if (typeof name !== "string") {
return false;
}
// gradeプロパティーが数値型かを判定
if (typeof grade !== "number") {
return false;
}
return true;
}
※引用元
その3
TypeScript を使って、データに関する型を定義する際に、class
とinterface
をいい感じに使い分けると思うのだけど、名前でどっちを使っているか分けわからなくなるので、とりまこんな命名で分けてみた。
文法 | 命名 |
---|---|
interface | api-format |
class | entity |
……違和感は残るよねw
てかTypeScript のinterface
って、シリアライズ対象になるデータ構造に対して利用するだっけ?
例えばJSON.parse()
したときに、class
で受け取っても、各メソッドの復元は行われないので、個人的に昔ハマった気がする。
そんなこと考えてたら、命名があーなっちゃったw
気を抜くと、こういうコード書いちゃう人なので、なにかしらの意識付けしないとまずいなと思っている今日この頃……。
class A {
constructor(
public prop: string
) {
}
fx() {
console.log(this.prop);
}
}
const a = new A("test");
const json = JSON.stringify(a);
const parsed = JSON.parse(json) as A;
parsed.fx(); // crash
その4
いまさら気付いたのだけど、MDN のブログ あるのか👀
今回の成果
- GitHub
- Nintendo Switch でトレーニングを進めた
- 本を読み進めた