LoginSignup
0
1

More than 3 years have passed since last update.

[メモ]TypeScriptのClassのコンストラクタの引数にオブジェクトを指定 (Generics使用)

Posted at

・Genericsでオブジェクト型をextendsしたTを指定した場合、T['プロパティ名']で特定プロパティの型を指定出来る。

// 引数に渡すオブジェクトの型 (interface)
interface PersonProps {
    name: string
    age: number
    gender: 'male' | 'female' | 'other'
}

// 引数の型をGenericsで指定し、PersonPropsをextendsして制約を設ける
class Person<T extends PersonProps>
{
    // T['name']でTの特定のプロパティの型を指定出来る
    private name: T['name']
    private age: T['age']
    private gender: T['gender']
    constructor (props: T) {
        this.name = props.name
        this.age = props.age
        this.gender = props.gender
    }

    public getName () {
        return this.name
    }

    public getAge () {
        return this.age
    }

    public getGender () {
        return this.gender
    }
}

// personPropsを定義
const personProps: PersonProps = {
    name: '俺やで',
    age: 23,
    gender: 'male'
}

const person = new Person(personProps)

console.log(uniquePerson2.getName()) // 俺やで
console.log(uniquePerson2.getAge()) // 23
console.log(uniquePerson2.getGender()) // male
0
1
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
0
1