0

I have a type where one of the properties is a class that takes that type as a parameter

interface Type<P extends {}> {
  name: string;
  props: P;
  field: new(type: Type<P>) => { ... };
}

// Define some Types
interface AllTypes {
  Foo: Type<{}>;
  Bar: Type<{
    foo: string;
    bar: number
  }>
}
type SomeType = AllTypes[keyof AllTypes];

I have a function that takes a SomeType and tries to instantiate its field, but I get an error

function f(type: SomeType) {
  return new type.field(type);  // Error
}

Changing Type.field to new(type: SomeType) => ... will solve this error, but will create further errors down the line:

class Field<T extends SomeType> {
  type: T;
  constructor(type: T) {
    this.type = type;
  }
}
declare class FooField extends Field<AllTypes['Foo']> {}
declare class BarField extends Field<AllTypes['Bar']> {}

const fields: SomeType[] = [
  {
    name: 'foo',
    props: {},
    field: FooField,
  },
  {
    name: 'bar',
    props: {  // This error is expected and desired
      foo: 0,
      bar: 'hi',
    },
    field: BarField,  // Error
  },
];

1 Answer 1

1

I think this is what you look for:

interface Type<P extends {}> {
  name: string;
  props: P;
  field: new<T extends Type<any>>(type: T) => { };
}
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.