简体   繁体   中英

Typescript, interfaces and variable declaration: what does it means?

This is part of a Material-UI interface:

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;
}


I tried the following assignment (it works:):

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

My question is: what does it means? Could I consider it as declaring a new variable that is a 'sub-type' of DialogProps? Where could I find some documentation about this topic in typescript?

Thank you

You can retrieve the type of a property when you access it like this: 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);

If you hover the red underlined text the compiler actually tells you that you can retrieve the type of a property using [propertyName] .

Didn't know that myself, documentation is here: https://github.com/Microsoft/TypeScript/blob/1db4f96fd14fc3de5ae3704e925afd6474cfb8f5/doc/spec.md#4.13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM