Reputation: 1835
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?
Upvotes: 6
Views: 1452
Reputation: 3756
Typescript interface inheritance is the way to go.
interface Props {
firstName: string;
lastName?: string;
}
interface DefaultProps {
lastName: string;
}
type PropsWithDefaults = Props & DefaultProps;
export class User extends React.Component<Props> {
public static defaultProps: DefaultProps = {
lastName: 'None',
}
public render () {
const { firstName, lastName } = this.props as PropsWithDefaults;
return (
<div>{firstName} {lastName}</div>
)
}
}
Upvotes: 0
Reputation: 6012
There is currently no way around this using the default react types on DefinitelyTyped. There is an open ticket on github tracking solutions to this.
Upvotes: 0
Reputation: 91
Adding an exclamation mark !
behind list
should help:
list!.map(item => (
<li>{item}</li>
))
Upvotes: 3