2016-11-24 79 views
3

我的TypeScript版本是2.0.10TypeScript + React:defaultProps不适用于严格空检查模式下的可选道具

组件

import * as React from "react"; 

export interface HelloProps { list?: number[]; } 

export class Hello extends React.Component<HelloProps, {}> { 
    static defaultProps = { 
     list: [1, 2, 3] 
    } 
    static propTypes = { 
     list: React.PropTypes.array, 
     title: React.PropTypes.string 
    }; 

    render() { 
     let {list} = this.props 
     return (
      <ul> 
       { 
        // error here: Object is possibly 'undefined'. 
        list.map(item => (
         <li>{item}</li> 
        )) 
       } 
      </ul> 
     ) 
    } 
} 

打字稿编译器配置文件

{ 
    "compilerOptions": { 
     "outDir": "./dist/", 
     "sourceMap": true, 
     "noImplicitAny": true, 
     "module": "commonjs", 
     "target": "es5", 
     "jsx": "react", 
     "strictNullChecks": true 
    }, 
    "include": [ 
     "src/**/*" 
    ] 
} 

注意,我设置strictNullCheckstrue这里。并编译输出:

ERROR in ./src/Hello.tsx 
(19,21): error TS2532: Object is possibly 'undefined'. 

但我已经设置列表的默认值。它是一个TypeScript错误?

回答

1

添加一个感叹号!背后list应该有所帮助:

list!.map(item => (
    <li>{item}</li> 
))