Захват типа массива, чтобы мы могли отобразить его в массив типов объединения - PullRequest
0 голосов
/ 17 ноября 2018
class Custom1 { }

class Custom2 { }

class Custom3 { }

class Custom4 { }

class Foo { 
  custom1s: Custom1[];
  custom2s: Custom2[];
  custom3: Custom3;
  custom4: Custom4;
}

type SomeMapping<T> = {
  [P in keyof T]
  : T[P] extends any[] ? object[]
  : (T[P] | object);
}

type FooMapped = SomeMapping<Foo>;

Фактическая типизация такова:

type FooMapped = { 
  custom1s: object[]; 
  custom2s: object[]; 
  custom3: object | Custom3; 
  custom4: object | Custom4; 
}

Что мне бы хотелось:

type FooMapped = { 
  custom1s: (object | Custom1)[]; 
  custom2s: (object | Custom2)[]; 
  custom3: object | Custom3; 
  custom4: object | Custom4; 
}

Как нам захватить тип массива, чтобы мы могли его повернутьв союз?

1 Ответ

0 голосов
/ 17 ноября 2018

Чтобы иметь тип

type FooMapped = { 
  custom1s: Custom1[]; 
  custom2s: Custom2[]; 
  custom3: object | Custom3; 
  custom4: object | Custom4; 
}

ты должен сделать это

type SomeMapping<T> = {
  [P in keyof T]
  : T[P] extends (infer U)[] ? U[]
  : (T[P] | object);
}

и для достижения этого типа

type FooMapped = { 
  custom1s: (object | Custom1)[]; 
  custom2s: (object | Custom2)[]; 
  custom3: object | Custom3; 
  custom4: object | Custom4; 
}

сделать это

type SomeMapping<T> = {
  [P in keyof T]
  : T[P] extends (infer U)[] ? (U | object)[]
  : (T[P] | object);
}

Ссылка: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html (раздел «Условные типы»)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...