Understanding TypeScript’s type notation
https://gyazo.com/b6a99d8a2fb71d683632b9e3ec685bef http://2ality.com/2018/04/type-notation-typescript.html
code:typescript
interface Array<T> {
concat(...items: Array<T[] | T>): T[];
reduce<U>(
callback: (state: U, element: T, index: number, array: T[]) => U,
firstState?: U): U;
···
}
これが読めるようになる。
code:Array List の表し方.ts
let arr: number[] = [];
let arr: Array<number> = [];
code:タプル.ts
code:rest と合わせて.ts
function joinNumbers(...nums: number[]): string {
return nums.join('-');
}
joinNumbers(1, 2, 3); // '1-2-3'
code:関数の結果型.ts
function stringify123(callback: (num: number) => string): string {
const num = 123;
return callback(num);
}
code:void 返すやつ.ts
function f1(): void { return undefined } // OK
function f2(): void { } // OK
function f3(): void { return 'abc' } // error
code:? で option.ts
function stringify123(callback?: (num: number) => string) {
const num = 123;
if (callback) {
return callback(num); // (A)
}
return String(num);
}
code:型付きデフォルト値.ts
function createPoint(x:number = 0, y:number = 0) {
}
code:複合的なやつ.ts
let x: null|number = null; // null または number
x = 123;
code:なるほどねー.ts
function stringify123(
callback: null | ((num: number) => string)) {
const num = 123;
if (callback) { // (A)
return callback(123); // (B)
}
return String(num);
}
code:似てるけど違う.ts
function f1(x?: number) { }
f1(); // OK
f1(undefined); // OK
f1(123); // OK
// 型パラメータは省略できない
function f2(x: undefined | number) { }
f2(); // error
f2(undefined); // OK
f2(123); // OK
null と undefined は TypeScript において別物で型の一部。
code:interface 経由でオブジェクトを受け取る.ts
interface Point {
x: number;
y: number;
}
function pointToString(p: Point) {
return (${p.x}, ${p.y});
}
pointToString({x: 5, y: 7}); // '(5, 7)'
code:interface でも ? 使えるし、method もいける.ts
interface Person {
name: string;
company?: string;
}
interface Point {
x: number;
y: number;
distance(other: Point): number;
}
code:型を <T> で表して.ts
interface Stack<T> {
push(x: T): void;
pop(): T;
}
const dummyStack: Stack<number> = {
push(x: number) {},
pop() { return 123 },
};
code:Map はこんな感じ.ts
const myMap: Map<boolean,string> = new Map([
]);
code:関数も型変数が使えるので.ts
function id<T>(x: T): T {
return x;
}
id<number>(123);
// または推論で
id(123);
code:型のパラメーター渡し.ts
function fillArray<T>(len: number, elem: T) {
return new Array<T>(len).fill(elem);
}
const arr = fillArray(3, '*');
// Inferred type: string[]
これはどんなときつかうんだろう。
See also