ジェネリックと型エイリアスを使用できます。これは多くのコードですが、うまくいきます。
interface School<T extends Teacher<PersonInfo>, S extends Student<PersonInfo>> {
teachers: Array<T>;
students: Array<S>;
}
type EditableSchool = School<EditableTeacher, EditableStudent>;
type ReadonlySchool = Readonly<School<ReadonlyTeacher, ReadonlyStudent>>;
interface Teacher<P extends PersonInfo> {
teacherId: number;
personInfo: P;
}
type EditableTeacher = Teacher<PersonInfo>;
type ReadonlyTeacher = Readonly<Teacher<Readonly<PersonInfo>>>;
interface Student<P extends PersonInfo> {
studentId: number;
personInfo: P;
}
type EditableStudent = Student<PersonInfo>;
type ReadonlyStudent = Readonly<Student<Readonly<PersonInfo>>>;
interface PersonInfo {
name: string;
age: number
}
var s: ReadonlySchool = {
teachers: [{teacherId: 1, personInfo: {name: "John", age: 40}}],
students: [{studentId: 1, personInfo: {name: "Dan", age: 20}}]
}
s.teachers = null;
s.teachers[0].personInfo.name = "John2"; // Cannot assign to 'name' because it is a constant or a read-only property
s.students[0].personInfo.age = 22; // Cannot assign to 'age' because it is a constant or a read-only property
(遊び場のコード)
編集
s.teachers[0] = nul
失敗したい場合は、Array
をReadonlyArray
に変更する必要もあります。
interface School<T extends Teacher<PersonInfo>, Ta extends ArrayLike<T>, S extends Student<PersonInfo>, Ts extends ArrayLike<S>> {
teachers: Ta;
students: Ts;
}
type EditableSchool = School<EditableTeacher, Array<EditableTeacher>, EditableStudent, Array<EditableStudent>>;
type ReadonlySchool = Readonly<School<ReadonlyTeacher, ReadonlyArray<ReadonlyTeacher>, ReadonlyStudent, ReadonlyArray<ReadonlyStudent>>>;
残りは同じですが、次のようになります。
s.teachers = null; // Cannot assign to 'teachers' because it is a constant or a read-only property
s.teachers[0] = null; // Index signature in type 'ReadonlyArray<Readonly<Teacher<Readonly<PersonInfo>>>>' only permits reading
確かに、これは単純な解決策ではなく、非常に冗長ですが、少なくとも今のところ、この問題に対する単純な一般的な解決策は存在しないと思います。
検討:
type ReadyonlyDeep<T> = {
readonly [P in keyof T]: ReadyonlyDeep<T[P]>;
}
オブジェクトに他の単純なオブジェクトしかない限り、これはうまく機能します。
interface A {
b: B
}
interface B {
str: string;
}
let a: ReadyonlyDeep<A>;
a.b.str = "fe"; // Cannot assign to 'str' because it is a constant or a read-only property
しかし、配列を導入すると:
interface B {
str: string;
moreB: B[];
}
それで:
a.b.moreB = []; // Cannot assign to 'moreB' because it is a constant or a read-only property
a.b.moreB[0].str = "hey"; // this is fine though
おそらく簡単に解決できる問題ではありません。