Typescript, интерфейсы и объявление переменных: что это значит? - PullRequest
1 голос
/ 29 апреля 2020

Это часть интерфейса Material-UI:

export interface DialogProps
  extends StandardProps<ModalProps & Partial<TransitionHandlerProps>, DialogClassKey, 'children'> {
  /**
   * The id(s) of the element(s) that describe the dialog.
   */      
  /**
   * If `true`, the dialog stretches to `maxWidth`.
   *
   * Notice that the dialog width grow is limited by the default margin.
   */
  fullWidth?: boolean;
  /**
   * Determine the max-width of the dialog.
   * The dialog width grows with the size of the screen.
   * Set to `false` to disable `maxWidth`.
   */
  maxWidth?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | false;
  /**
   * Callback fired when the backdrop is clicked.
   */      
  /**
   * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element.
   */
  TransitionProps?: TransitionProps;
}

Я попробовал следующее задание (оно работает!):

const maxWidth: DialogProps['maxWidth'] = 'lg' 

Мой вопрос: что это значит? Могу ли я считать это объявлением новой переменной, которая является «подтипом» DialogProps? Где я могу найти документацию об этой топике c в машинописном тексте?

Спасибо

1 Ответ

1 голос
/ 29 апреля 2020

Вы можете получить тип свойства при доступе к нему следующим образом: DialogProps['maxWidth']

export interface DialogProps {
  /**
   * The id(s) of the element(s) that describe the dialog.
   */      
  /**
   * If `true`, the dialog stretches to `maxWidth`.
   *
   * Notice that the dialog width grow is limited by the default margin.
   */
  fullWidth: boolean;
  /**
   * Determine the max-width of the dialog.
   * The dialog width grows with the size of the screen.
   * Set to `false` to disable `maxWidth`.
   */
  maxWidth: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | false;     
}


const maxWidth: DialogProps.maxWidth = 'lg' 

console.log(maxWidth);

Если вы наведете курсор мыши на красный подчеркнутый текст, компилятор фактически скажет вам, что вы можете получить тип собственность с использованием [propertyName].

Сам не знал, документация здесь: https://github.com/Microsoft/TypeScript/blob/1db4f96fd14fc3de5ae3704e925afd6474cfb8f5/doc/spec.md#4 .13

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