enforce class A to have only interface parameter name only
interface I {
name: string;
}
Class A implements I{
name: string;
age: string; <= it should generate error
}
enforce class A to have only interface parameter name only
interface I {
name: string;
}
Class A implements I{
name: string;
age: string; <= it should generate error
}
I'm not sure why you need this, but you can use a recursively bounded type to get the desired behavior, as long as you're willing to mention the class name twice in your definition:
type Exactly<T, U extends T> = { [K in keyof U]: K extends keyof T ? T[K] : never }
class A implements Exactly<I, A> {
name: string = "needs initialization";
age: string = "me too" // error!
// ~~~ <--- string is not assignable to never
}
The type Exactly<T, U> is a mapped type with conditional properties. The output of Exactly<T, U> has all the same keys as U, but the values for any keys no in T are of type never.
The constraint U extends T means that U must have at least all the properties of T. And the constraint in class U implements Exactly<T, U> means that U must not have any defined properties not found in T, or else U could not match Exactly<T, U>.
In the above code example, A is something like {name: string, age: number}. And Exactly<I, A> evaluates to {name: string, age: never}. So the constraint class A implements Exactly<I, A> is not met, because {name: string, age: number} does not implement{name: string, age: never}. The problem is in the age property, so you get an error where you want it.
Okay, hope that helps; good luck!