0

Given a Type:

type TestType = {
  a?: string;
  b?: number;
  c?: boolean;
};

I want to create a class that implements TestType with all its properties names where the types could be different.

If not, raise an error.

I've tried with Pick, Required, etc. without success.

Example (error):

/* Error, not all TestType properties are implemented */
class TestClass implements TestType {}

Example (correct):

class TestClass implemenets TestType {
  a?: boolean;   // Different type
  b?: number;    // Same type
  c?: string;    // Different type
}

Can this be achieved with Typescript?

Thanks!

Carlo Corradini
  • 2,927
  • 2
  • 18
  • 24
  • If you say `TestClass` is an implementation (or child or whatever) of `TestType` then the expectation is that `TestClass` can be used wherever `TestType` is used. Yet you are breaking that relationship. Are you sure this is exactly what you want? Is this possible [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? – VLAZ May 10 '22 at 14:34

1 Answers1

0

We can make a utility type called ToAny for this:

type ToAny<T> = {[K in keyof T]: any}

Usage:

class TestClass implements ToAny<TestType> {}

class TestClass2 implements ToAny<TestType> {
  a?: boolean;   // Different type
  b?: number;    // Same type
  c?: string;    // Different type
}
Tobias S.
  • 21,159
  • 4
  • 27
  • 45