Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/generics/lib.generics.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
type Record<K extends string | number | symbol, T> = { [P in K]: T; };
type Partial<T> = { [P in keyof T]?: T[P] | undefined; }
type Required<T> = { [P in keyof T]-?: T[P]; }
type Readonly<T> = { readonly [P in keyof T]: T[P]; }
// A class is kept as it is: mapped, it would become an object of its fields, a copy without its methods.
// Nothing is lost - a class's fields are always there, and readonly is only checked when compiling.
// (`extends abstract new` is true of a class itself in tslang, not only of its constructor.)
type Required<T> = T extends abstract new (...args: any) => any ? T : { [P in keyof T]-?: T[P]; }
type Readonly<T> = T extends abstract new (...args: any) => any ? T : { readonly [P in keyof T]: T[P]; }
type Pick<T, K extends keyof T> = { [P in K]: T[P]; }
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
Expand Down
69 changes: 69 additions & 0 deletions tests/readonly_required_class.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Readonly<C> and Required<C> of a class are the class itself: mapped, a class became an object of
// its fields, a copy without its methods (Readonly<C> of a class with methods came out empty). Of
// an object type they are still mapped.
class Counter {
count = 1;

bump() {
this.count++;
}
}

class Opt {
y?: number;

show() {
return "opt";
}
}

class Base {
constructor(public x: number) {}
}

class Derived extends Base {
twice() {
return this.x * 2;
}
}

class Box<T> {
constructor(public value: T) {}

get() {
return this.value;
}
}

interface Point {
x: number;
y?: number;
}

function main() {
// the same instance: a call through it reaches the original
const c = new Counter();
const r: Readonly<Counter> = c;
r.bump();
assert(c.count == 2 && r.count == 2, "Readonly of a class is the class");

const o = new Opt();
const q: Required<Opt> = o;
assert(q.show() == "opt", "Required of a class is the class");

// a class whose constructor takes arguments, a derived one, a generic one
const d: Readonly<Derived> = new Derived(3);
assert(d.twice() == 6, "Readonly of a derived class");

const b: Required<Box<string>> = new Box<string>("v");
assert(b.get() == "v", "Required of a generic class");

// object types are mapped as before
const p: Readonly<{ a: number }> = { a: 5 };
assert(p.a == 5, "Readonly of an object type");

const pt: Required<Point> = { x: 1, y: 2 };
assert(pt.x == 1 && pt.y == 2, "Required of an interface");

print("ALL DONE");
}
Loading