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

时间:2016-11-24 08:44:00

标签: typescript typescript2.0

我的TypeScript版本为2.0.10

组件

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

TypeScript编译器配置文件

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

请注意,我在这里将strictNullChecks设置为true。编译输出:

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

但是我已经为list设置了默认值。它是TypeScript错误吗?

4 个答案:

答案 0 :(得分:2)

!后添加感叹号list应该会有所帮助:

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

答案 1 :(得分:0)

目前无法使用DefinitelyTyped上的默认反应类型。有一个open ticket on github跟踪解决方案。

答案 2 :(得分:0)

TypeScript 3.0支持这一点。

答案 3 :(得分:0)

打字稿interface inheritance是解决之道。

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