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

问题描述 投票:4回答:4

我的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错误吗?

typescript typescript2.0
4个回答
2
投票

!后面添加感叹号list应该有助于:

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

0
投票

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


0
投票

TypeScript 3.0支持这一点。


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>
    )
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.