打字稿,接口和变量声明:这是什么意思?

时间:2020-04-29 10:18:59

标签: typescript

这是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的“子类型”吗?在哪里可以在打字稿中找到有关此主题的一些文档?

谢谢

1 个答案:

答案 0 :(得分:1)

像这样访问属性时,您可以检索属性的类型: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