Given a base type A, I am looking to create a sub-type B that is assignable to A without any additional properties, and enforce this assignability.
Illustration
Starting with the following type:
interface A {
name?: string;
age?: number;
}
I aim to establish the following type:
interface B {
name: string;
}
In essence, any instance of type B should be assignable to type A, maintaining strict adherence. If any extra property is added, TypeScript should raise an error.
Potential Pitfalls
- Utilizing extends might lead to a less stringent result than desired:
interface B extends A {
name: string;
}
This formulates as:
interface B {
name: string;
age?: number;
}
Furthermore, it permits adding non-existent properties for Person.
- The approach of
A extends B
is not viable due to A already being predetermined; the goal is to craft type B.