TypeScript 型
TypeScriptの型入門
プリミティブ型
普通の型. number, string, ...
リテラル型
code:ts
// 型は合併型で複数列挙できる (Union型という)
type BirthYear = number | string;
// 型には値も設定できる
type FoodMenu = "北極" | "冷やし味噌";
// 北極と冷やし味噌以外は許されない型になる.
// これをTypeエイリアスという
// 変数や関数の引数で使える
const birthday: BirthYear = "平成";
function orderFood(food: FoodMenu) {
}
リテラル型と型推論
code:ts
const a = 'foo'; // aは'foo'型を持つ
const b: 'bar' = a; // エラー: Type '"foo"' is not assignable to type '"bar"'.
let a = 'foo'; // aはstring型に推論される
const b: string = a;
const c: 'foo' = a; // エラー: Type 'string' is not assignable to type '"foo"'.
let a: 'foo' = 'foo';
a = 'bar'; // エラー: Type '"bar"' is not assignable to type '"foo"'.
オブジェクト型
code:ts
interface MyObj {
foo: string;
bar: number;
}
const a: MyObj = {
foo: 'foo',
bar: 3,
};
配列型
code:ts
const foo: number[] = 0, 1, 2, 3;
foo.push(4);
関数
code:ts
const f: (foo: string)=> number = func;
function func(arg: string): number {
return Number(arg);
}
unknown型
code:ts
let unknownInput: unknown;
let anyInput: any;
let text: string;
unknownInput = 'hello';
unknownInput = 21;
unknownInput = true;
text = anyInput;
if (typeof unknownInput === 'string'){ // このチェックが必要. ここでunknownInputはstring型になった
text = unknownInput;
}
never型
型を持たない型
code:ts
let foo: never = 123; // Error: Type number is not assignable to never
// Okay as the function's return type is never
let bar: never = (() => { throw new Error(Throw my hands in the air like I just don't care) })();
never - TypeScript Deep Dive 日本語版
Enum
code:ts
enum MOBILE_OS {
IOS, // 0
ANDROID // 1
}
TypeScriptのenumを使わないほうがいい理由を、Tree-shakingの観点で紹介します - LINE ENGINEERING
#TypeScript