gpt4 book ai didi

typescript + react : defaultProps not works for optional props in strict null checking mode

转载 作者:搜寻专家 更新时间:2023-10-30 20:43:41 25 4
gpt4 key购买 nike

我的 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'.

但我已经为列表设置了默认值。这是 typescript 错误吗?

最佳答案

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

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

关于 typescript + react : defaultProps not works for optional props in strict null checking mode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com