简体   繁体   中英

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?

Adding an exclamation mark ! behind list should help:

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

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.

TypeScript 3.0支持此功能。

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>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM