[A-00194] Typescript入門
typescript入門用の記事です。
主にdenoを使って実行します。
・Helloworldしてみる
console.log("Hello,typescript!");
下記のコマンドで実行します。
deno run hello.ts
$ deno run hello.ts
Hello,typescript!
・クラスを作ってみる
次はクラスを作ってみます。ディレクトリ構成は下記の通りです。
personクラスを作成します。
export class Person {
name: string;
age: number;
address: string;
constructor(name: string, age: number, address: string) {
this.name = name;
this.age = age;
this.address = address;
}
private sayName(): void {
console.log("My name is " + this.name + "!");
}
public getName(): string {
this.sayName();
return this.name;
}
}
次に実行するプログラムを書きます。
import { Person } from './clsdir/person.ts'
const p1 = new Person('takeshi', 14, 'tokyo');
var name:string = p1.getName();
console.log("His name is " + name + ".");
実行すると下記にようになります。
$ deno run main.ts
My name is takeshi!
His name is takeshi.
・インターフェースを作ってみる
先ほど作成したPersonをインターフェースにしてBusinessPersonクラスを実装してみます。
export interface Person {
getName():string;
getAge():number;
getAddress():string;
getCountry():string;
}
import { Person } from './person.ts';
export class BusinessPerson implements Person {
private name: string;
private age: number;
protected address: string;
private country: string;
private job: string;
public constructor(name:string, age:number,
address:string, country:string, job:string) {
this.name = name;
this.age = age;
this.address = address;
this.country = country;
this.job = job;
}
public introduce(): void {
console.log("Nice to meet you.");
console.log("My name is " + this.name + ". I'm " + this.age + " years old.");
console.log("I'm now live in " + this.country + ", at " + this.address + ". ");
console.log("I'm work as " + this.job);
}
public getName(): string {
return this.name;
}
public getAge(): number {
return this.age;
}
public getAddress(): string {
return this.address;
}
public getCountry(): string {
return this.country;
}
}
下記が実行プログラムです。
import { BusinessPerson } from './clsdir/business_person.ts'
const bp1 = new BusinessPerson("takeshi", 14 , "tokyo", "Japan", "student");
bp1.introduce();
$ deno run main.ts
Nice to meet you.
My name is takeshi. I'm 14 years old.
I'm now live in Japan, at tokyo.
I'm work as student
・Appendix
参考文献はこちら
https://qiita.com/nogson/items/86b47ee6947f505f6a7b
https://qiita.com/Tsuyoshi84/items/e74109e2ccc0f4e625aa
https://qiita.com/tatsumin0206/items/5835a64cb32ace41e0b1
https://qiita.com/kushidangoAnne/items/85c147aa694e4e6cc008
https://qiita.com/yukiji/items/3db06601ece7f080b0d0
https://zenn.dev/estra/books/ts-the-minimum/viewer/2-tsmini-start-deno-ts
コメントを残す