Home > Software engineering >  Is there a way to dynamically map keys to getters/setters of different types in Typescript?
Is there a way to dynamically map keys to getters/setters of different types in Typescript?

Time:08-02

I can create a type with different types for getter/setters like so:

type Example = {
   get prop(): number;
   set prop(value: any);
}

I can also map keys to different values:

type Mapped<T extends Object> = {
    [Key in keyof T]: T[Key] | boolean;
}

Is there a way to map keys to getters/setters? Something like:

type MappedAccessors<T extends Object> = {
    get [Key in keyof T](): T[Key];
    set [Key in keyof T](value: any);
}

CodePudding user response:

I know these are not real getters and setters but it mimics the behaviour.

type Example = {
  prop: number;
};

type Mapped<T> = {
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
} & {
  [K in keyof T as `set${Capitalize<K & string>}`]: (
    value: T[K]
  ) => void;
};

type MappedExample = Mapped<Example>;

// type MappedExample = {
//   getProp: () => number;
//   setProp: (value: number) => void;
// }

CodePudding user response:

Unfortunately there is no way currently to do this

Actually there is an open feature request for it : https://github.com/microsoft/TypeScript/issues/43662

  • Related