JY-CONTENTS

JY

JY-CONTENTS
search

+

MENU

【Typescript】マップ型

【Typescript】マップ型

(DATE)

-

2020.06.26

(CATEGORY)

-

基本

type A = 1|2|3
type B = {
    //type Aの値をキーに、stringに対応付け(マッピング)
    [Key in A]: string
}

//Bは以下のようになる
// {
//     1:string
//     2:string
//     3:string
// }

let obj:B = {
    1:"",
    2:"",
    3:""
}

応用

ルックアップ型と組み合わせると、どの値の型がどのキーの名前に対応するかを制約できます。
以下は User型をマッピングして、それぞれの制約を加えています。

type User = {
    id: number
    name: string
    notes: string[]
}

すべてのフィールドを省略可能にする

type Optional = {
    [K in keyof User]?: User[K]
}

// 上記は以下のようになる
// type Optional = {
//     [K in 'id' | 'name' | 'notes']?: User[K]
// }
// ▼
// ▼
// type Optional = {
//     id?: User['id']
//     name?: User['name']
//     notes?: User['notes']
// }
// ▼
// ▼
// type Optional = {
//     id?: number
//     name?: string
//     notes?: string[]
// }

// 全てoptionになる
let a: Optional = {} //ok

keyof 演算子

すべてのフィールドを null 許容にする

type Nullable = {
    [K in keyof User]: User[K] | null
}

//ok
let b: Nullable = {
    id: 10,
    name: "itou",
    notes: [""]
}

//ok
let b2: Nullable = {
    id: null,
    name: null,
    notes: null
}

すべてのフィールドを読み取り専用にする

type Readonlys = {
    readonly [K in keyof User]: User[K]
}

let c: Readonlys = {
    id: 10,
    name: "itou",
    notes: [""]
}

c.id = 20 //エラー
c.isEmployee = 'suzuki' //エラー
c.notes[0] = "" //エラー

組み込みのマップ型

TypeScript あらかじめ組み込まれているマップ型です。

Record < Keys, Values >

Keys 型のキーとValues 型の値を持つオブジェクト。

Partial < Object >

Object 内のすべてのフィールドを省略可能と指定します。

Required < Object >

Object 内のすべてのフィールドを必須(省略不可)と指定します。

Readonly < Object >

Object 内のすべてのフィールドを読み取り専用と指定します。

Pick < Object, Keys >

指定された Keys だけを持つ、Object のサブタイプを返します。

NEW TOPICS

/ ニュー & アップデート

SEE ALSO

/ 似た記事を見る

JY CONTENTS UNIQUE BLOG

search-menu search-menu