Open17
typescript
null vs undefined
TypeScriptチームは、nullを使いません: TypeScriptコーディングガイドライン。 そして、問題は起きていません。 Douglas Crockfordはnullは良くない考えであり、誰もがundefinedだけを使うべきだと考えています。
null undefinedの除外
== nullを使ってundefinedと nullを両方ともチェックすることを推奨します。一般的に2つを区別する必要はありません。
function foo(arg: string | null | undefined) {
if (arg != null) {
// `!=` がnullとundefinedを除外しているので、引数argは文字列です
}
}
値をgetする関数の戻り値の型について
取得に失敗した場合はどうするか
推奨は分からず。。
↓一応公式で見つけた一文を。
const numOrFalse: number | false = union();
Jsonデータのバリデーションチェック
zodが便利
Jsonの型
いずれかひとつが必須
expressのreq,res,nextの型付け
eslint エラー
This rule requires the `strictNullChecks` compiler option to be turned on to function correctly
# '@typescript-eslint/strict-boolean-expressions': ['error', { # boolean型が予測される式(if文の条件句)でboolean型以外の使用を禁止 デフォルトで、string型とnumber型とオブジェクト型は許可されているため禁止にする
# 'allowString': false,
# 'allowNumber': false,
# 'allowNullableObject': false
# }]
三項演算子とか使えなくなるのでこのルールはつけないことにした
enumの型ガード
export const Exit = {
Unlisted: '未上場',
Buyout: 'バイアウト',
Listed: '上場',
} as const
export type Exit = typeof Exit[keyof typeof Exit]
export const isExit = (token: any): token is Exit => {
return Object.values(Exit).includes(token)
}