LoginSignup
2
0

More than 3 years have passed since last update.

TypeScriptでよく作るClass

Last updated at Posted at 2019-06-04

サーバーサイド(Cloud Functions)でしかTypeScriptを書いた事が無いのでクライアントサイドは謎。

export type DogData = {
    id?: string;
    name: string;
    race?: string;
}

//Type Guard
export const dataIsDogData = (data: any): data is DogData => {
    const d = data as DogData;
    if (typeof d.name !== 'string') return false;
    return true
}

export class Dog implements DogData {

    readonly id: string;
    readonly name: string;
    readonly race?: string;

    constructor(data: any) {
        if (!dataIsDogData(data)) throw new Error(data is not DogData `${JSON.stringify(data)}`);
        Object.assign(this, data);
        this.id = generateId(data);
        this.name = data.name;
    }
}

メソッドが欲しくならない限りtype定義だけして済ませる事が多いのだけれど、欲しくなったらこういうの用意して

//Barrel
import * as entity from '../Entity';

createDog = (incomingData: any): entity.Dog | undefined => {
    const dogData: entity.dogData = {
        ...incomingData,
        name: 'Dogmeat',
    };
    if (!entity.dataIsDogData(dogData)) return undefined;
    return new entity.Dog(dogData);
}

createDog({
  race: ''
})

みたいな感じでよく使ってる。プロパティが増えるとやや煩雑なので、どうしようかなと思ってる。あとconstructorでanyを受けちゃうのはちょっとお行儀悪い。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0