Typescript 打字脚本+;反应:默认道具不适用于严格空检查模式下的可选道具
我的打字脚本版本是Typescript 打字脚本+;反应:默认道具不适用于严格空检查模式下的可选道具,typescript,typescript2.0,Typescript,Typescript2.0,我的打字脚本版本是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 =
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>
)
}
}
注意,我在这里将stricnullchecks
设置为true
。以及编译输出:
ERROR in ./src/Hello.tsx
(19,21): error TS2532: Object is possibly 'undefined'.
但我已经为列表设置了默认值。这是一个打字脚本错误吗 添加感叹号
代码>后面列表
应有助于:
list!。地图(项目=>(
{item}
))
目前,在DefinitelyTyped上使用默认的react类型无法解决此问题。对此有一个跟踪解决方案。支持此功能。Typescript是一个不错的选择
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>
)
}
}
界面道具{
名字:字符串;
lastName?:字符串;
}
界面默认道具{
lastName:string;
}
键入PropsWithDefaults=Props&DefaultProps;
导出类用户扩展React.Component{
公共静态defaultProps:defaultProps={
姓氏:“无”,
}
公开渲染(){
const{firstName,lastName}=this.props作为PropsWithDefaults;
返回(
{firstName}{lastName}
)
}
}
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>
)
}
}