Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript + React: defaultProps not works for optional props in strict null checking mode

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?

like image 929
clinyong Avatar asked Nov 24 '16 08:11

clinyong


1 Answers

Adding an exclamation mark ! behind list should help:

list!.map(item => (
    <li>{item}</li>
))
like image 103
fhå Avatar answered Oct 24 '22 07:10

fhå