clinyong
clinyong

Reputation: 1835

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?

Upvotes: 6

Views: 1452

Answers (4)

Morlo Mbakop
Morlo Mbakop

Reputation: 3756

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

Upvotes: 0

clinyong
clinyong

Reputation: 1835

TypeScript 3.0 has supported this.

Upvotes: 0

Cameron Martin
Cameron Martin

Reputation: 6012

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.

Upvotes: 0

fh&#229;
fh&#229;

Reputation: 91

Adding an exclamation mark ! behind list should help:

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

Upvotes: 3

Related Questions