Nullish Coalescing
- TypeScriptの3.7.0から利用出来る機能
- undefined またはnullの場合だけ、指定した値が設定される
const userDate = downloadedDate.user ?? 'dummy-date'
||
の違いは、この場合、0や空文字の場合も指定された値が設定される
const userDate = downloadedDate.user || 'dummy-date'
LookUp型
- 構文的には、要素アクセスとまったく同じように見えますが、タイプとして記述されます。
https://www.bookstack.cn/read/typescript-3.8-en/055dccf6c3f8aae3.md#keyof%20and%20Lookup%20Types
interface UserDate { id: number user: { name?: { first: string; last: string; } } } type id = UserDate["id"] type id2 = UserDate["user"] type id3 = UserDate["id" | "user"]
型の互換性
- 全部覚えるのは厳しいので、必要になったときに覚える 参考文献 https://github.com/microsoft/TypeScript/blob/master/doc/spec.md#311-type-relationships
interface Named { name: string; } class Person { name: string; } let p: Named; // OK, because of structural typing p = new Person();
関数のオーバーロードをインターフェースで定義する場合
interface TempFunc { (x: string): string, (x: number): string; } const upperHello: TempFunc = function (x: string | number) { return 'test' }
関数型のインターセクションはオーバーロードになる
- 下記の場合、AのFunctionから優先的に読み込まれる。&の指定を逆にすると優先順位が逆になる
interface TempFuncA { (x: string): number, (x: number): number; } interface TempFuncB { (y: string): number, } let intersectionFunction: TempFuncA & TempFuncB intersectionFunction = function (a: number | string, b?: number | string) { return 0 }
レストパラメータ
- レストパラメータの色々な利用方法
function TempFuncA(...args: number[]) { } TempFuncA(1, 2, 3, 5, 6, 7) function TempFuncB(...args: [string, number, boolean]) { } TempFuncB('test', 1, false) function TempFuncC(...args: [string, number?, boolean?, ...number[]]) { } TempFuncC('test', 1, false, 111, 222, 333) function TempFuncD(...args: readonly [string, number?, boolean?, ...number[]]) { } TempFuncD('test', 1, false, 111, 222, 333)
cconstのアサーション
- 全部定数として指定できる。readonly修飾子が自動でつく
const array = [10, 20] as const const engineer = { name: 'Yamada', age: 43 } as const