Обусловленный машинописным текстом динамический c объявление типа модели - PullRequest
0 голосов
/ 06 августа 2020

Есть ли в машинописном тексте что-то вроде объявления типа Dynami c, где на основе типа переменной значения будет назначена правильная пользовательская модель?

export type ModelDeclaration = {
 [T: string]: typeof ModelDeclaration[T] === 'string' ? ModelStringInput : ModelIntInput;
}

export type ModelIntInput = {
    between?: Array<number | null> | null;
    attributeExists?: boolean | null;
    attributeType?: ModelAttributeTypes | null;
};

export type ModelStringInput = {
    attributeType?: ModelAttributeTypes | null;
    size?: ModelSizeInput | null;
};

Ответы [ 2 ]

1 голос
/ 06 августа 2020

Что вы можете сделать, так это использовать переменную для различения двух вариантов:

export type ModelDeclaration = 
{
 value: string
 type: 'string'
 model: ModelStringInput
} |
{
 value: number
 type: 'int'
 model: ModelIntInput
}

export type ModelIntInput = {
    between?: Array<number | null> | null;
    attributeExists?: boolean | null;
    attributeType?: ModelAttributeTypes | null;
};

export type ModelStringInput = {
    attributeType?: ModelAttributeTypes | null;
    size?: ModelSizeInput | null;
};


const parseModel = (model: ModelDeclaration) => {
  if (model.type === 'string') {
     // Here typescript knows that model.model is ModelStringInput and model.value is string
  }

  if (model.type === 'int') {
     // Here typescript knows that model.model is ModelIntInput and model.value is number
  }
}
1 голос
/ 06 августа 2020

Да, такие есть! Однако они немного ограничены в некоторых аспектах, на мой взгляд, руководство объясняет это довольно хорошо: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

Однако ваш пример выглядит так, будто вы могли бы просто написать функцию, в которой вы обертываете это в

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