0
0

【Typescript】イミュータブルオブジェクトの不変性の担保範囲

Posted at

すべてImmutableなフィールドの場合

class AllImmutable {

    constructor(
        public readonly num: number,
        public readonly bool: boolean
    ) {

    }

}

これは、すべてImmutableであることは自明

子オブジェクトまでImmutableな場合

class Parents {

    constructor(
        public readonly num: number,
        public readonly child1: Child1,
    ) {

    }

}

class Child1 {
    constructor(
        public readonly num: number,
    ) {

    }
}

子オブジェクトがすべてImmutableなフィールドであるため、
子オブジェクトはImmutableであると言える。

また、親オブジェクトは、子オブジェクトがImmutableであるため、
フィールドnumとchild1、すべてがImmutableである。
よって、親オブジェクトもImmutableであるといえる。

また、これは再帰的に適用できる。

class Parents {

    constructor(
        public readonly child1: Child1,
    ) {

    }

}

class Child1 {
    constructor(
        public readonly child2: Child2,
    ) {

    }
}

class Child2 {
    constructor(
        public readonly num: number,
    ) {

    }
}

Child2はImmutableであるから、Child1の持つフィールドはすべてImmutableである。
-> Child1はImmutableである。
Child1はImmutableであるから、Parentsの持つフィールドはすべてImmutableである。
-> ParentsはImmutableである。
の論法が成り立つ。
このように、自身がImmutableである場合、
Immutableの保証はまた親方向に伝播させることができる。

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