Default property value in React component using TypeScript

前端 未结 7 1063
温柔的废话
温柔的废话 2020-11-28 01:51

I can\'t figure out how to set default property values for my components using Typescript.

This is the source code:

class PageState
{
}

export class         


        
7条回答
  •  天涯浪人
    2020-11-28 02:01

    From a comment by @pamelus on the accepted answer:

    You either have to make all interface properties optional (bad) or specify default value also for all required fields (unnecessary boilerplate) or avoid specifying type on defaultProps.

    Actually you can use Typescript's interface inheritance. The resulting code is only a little bit more verbose.

    interface OptionalGoogleAdsProps {
        format?: string;
        className?: string;
        style?: any;
        scriptSrc?: string
    }
    
    interface GoogleAdsProps extends OptionalGoogleAdsProps {
        client: string;
        slot: string;
    }
    
    
    /**
     * Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
     */
    export default class GoogleAds extends React.Component {
        public static defaultProps: OptionalGoogleAdsProps = {
            format: "auto",
            style: { display: 'block' },
            scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
        };
    

提交回复
热议问题