1

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 
}
6
  • 3
    Why do you need that? A class can implement multiple interfaces, and have other props on top of that. Commented Dec 28, 2019 at 18:15
  • I am using multiple models like for backend and multiple frontends that is why I want to strict the schema for everyone Commented Dec 28, 2019 at 18:31
  • 1
    That's not really an explanation. If you access them via the interface you can only use the props defined on that interface anyway. Commented Dec 28, 2019 at 18:34
  • is there any other way to strict the class to have only those props which have defined for that? Commented Dec 28, 2019 at 18:41
  • It's really not clear why you still think you want this, but to be explicit: no. Commented Dec 28, 2019 at 18:45

1 Answer 1

2

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!

Playground Link to code

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.