【TypeScript】Getting Started
インストール
npm install -g typescript
Hello World
hello.ts
function hello() { return "Hello World"; } console.log(hello());
コンパイル
tsc hello.ts
hello.jsが生成される
型アノテーション
function hello(name: string) { return "Hello " + name; } console.log(hello('taro'));
以下だとコンパイルエラーとなる。
function hello(name: string) { return "Hello " + name; } console.log(hello(2));
error TS2345: Argument of type '2' is not assignable to parameter of type 'string'.
インタフェース
interface Person { name: string; age: number; } function hello(person: Person) { return `My Name is ${person.name}. I'm ${person.age} years old.`; } const taro = {name: "Taro", age: 18}; console.log(hello(taro));
クラス
コンストラクタの引数にpublic
を付ければクラスプロパティにできる。
class Person { fullName: string; constructor(public firstName: string, lastName: string) { this.fullName = firstName + " " + lastName; } } function hello(person: Person) { return `Hello ${person.fullName}`; } const taro = new Person('Suzuki', 'Taro'); console.log(hello(taro));
型の種類
- boolean
- number
- string
- array(2通り)
- number[]
- Array<number>
- [string, number]:タプル型(複数の型を含めた配列相当)
- enum
- `enum UserType {ADMIN, NORMAL}
- any
- void
- object
- undefined
- null
- never
型アサーション
const anyVal: any = "sample"; console.log((<string>anyVal).length); console.log((anyVal as string).length);