LoginSignup
3
3

More than 3 years have passed since last update.

TypeScriptの型定義毎のObjectに対するプロパティの追加可否

Posted at

やったこと

Objectの型定義の仕方によって、定義に無いプロパティの追加や不足を許容するかが変わってくるため、試してみた

コード

/**
 * - プロパティ追加不可
 * - プロパティ不足不可
 */
type UserNotAddProperty = {
    name: string
    age: number
}

const userA: UserNotAddProperty = {
    name: 'より',
    age: 22,
}

/**
 * - プロパティ追加可
 * - プロパティ不足不可
 */
type UserAddProperty = {
    name: string
    // インデックスシグネチャ・・string型のキーにstring | number型の値
    // ただし、keyが数値の場合もstringにキャストされる
    // keyの型はstring or numberのみ
    [key: string]: string | number // string or number型の値が入る
}

const userB: UserAddProperty = {
    name: 'ひろ', // これが無いとコンパイルエラー
    type: 'おたく', // 定義してないプロパティを追加出来る
    tall: 178, // 定義してないプロパティを追加出来る
    11: 192 // 定義してないプロパティを追加出来る
}

/**
 * - プロパティ追加不可
 * - プロパティ不足可 
 */
type UserWiding = {
    name?: string
    age?: number
}

const userC: UserWiding = {
    name: 'かつ'
}

プロパティをUnion型で定義も出来る

/**
 * - プロパティの値をUnion型で定義
 */
type Answer = 'a' | 'b' | 'c' | 'd'
type Question = 'question1' | 'question2'
type Target = {
    name: string
    answer: {
        // ?がついているので、プロパティが不足しててもOK
        [key in Question]? : Answer
    }
}

const target: Target = {
    name: 'MyName',
    // answerが無いとエラーになる
    answer: {
        // question2がなくてもエラーにならない
        question1: 'c',
    }
}

3
3
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
3
3