My TypeScript version is 2.0.10
.
The component
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>
)
}
}
The TypeScript compiler config file
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"strictNullChecks": true
},
"include": [
"src/**/*"
]
}
Note that I set strictNullChecks
to true
here. And the compile output:
ERROR in ./src/Hello.tsx
(19,21): error TS2532: Object is possibly 'undefined'.
But I have set the default value for list. Is it a TypeScript bug?
Adding an exclamation mark !
behind list
should help:
list!.map(item => (
<li>{item}</li>
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With