Default props with class component

Using static defaultProps is correct. You should also be using interfaces, not classes, for the props and state.

Update 2018/12/1: TypeScript has improved the type-checking related to defaultProps over time. Read on for latest and greatest usage down to older usages and issues.

For TypeScript 3.0 and up

TypeScript specifically added support for defaultProps to make type-checking work how you'd expect. Example:

interface PageProps {
  foo: string;
  bar: string;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, { this.props.foo.toUpperCase() }</span>
        );
    }
}

Which can be rendered and compile without passing a foo attribute:

<PageComponent bar={ "hello" } />

Note that:

  • foo is not marked optional (ie foo?: string) even though it's not required as a JSX attribute. Marking as optional would mean that it could be undefined, but in fact it never will be undefined because defaultProps provides a default value. Think of it similar to how you can mark a function parameter optional, or with a default value, but not both, yet both mean the call doesn't need to specify a value. TypeScript 3.0+ treats defaultProps in a similar way, which is really cool for React users!
  • The defaultProps has no explicit type annotation. Its type is inferred and used by the compiler to determine which JSX attributes are required. You could use defaultProps: Pick<PageProps, "foo"> to ensure defaultProps matches a sub-set of PageProps. More on this caveat is explained here.
  • This requires @types/react version 16.4.11 to work properly.

For TypeScript 2.1 until 3.0

Before TypeScript 3.0 implemented compiler support for defaultProps you could still make use of it, and it worked 100% with React at runtime, but since TypeScript only considered props when checking for JSX attributes you'd have to mark props that have defaults as optional with ?. Example:

interface PageProps {
    foo?: string;
    bar: number;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps: Partial<PageProps> = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, world</span>
        );
    }
}

Note that:

  • It's a good idea to annotate defaultProps with Partial<> so that it type-checks against your props, but you don't have to supply every required property with a default value, which makes no sense since required properties should never need a default.
  • When using strictNullChecks the value of this.props.foo will be possibly undefined and require a non-null assertion (ie this.props.foo!) or type-guard (ie if (this.props.foo) ...) to remove undefined. This is annoying since the default prop value means it actually will never be undefined, but TS didn't understand this flow. That's one of the main reasons TS 3.0 added explicit support for defaultProps.

Before TypeScript 2.1

This works the same but you don't have Partial types, so just omit Partial<> and either supply default values for all required props (even though those defaults will never be used) or omit the explicit type annotation completely.

Default props with Functional Components

You can use defaultProps on function components as well, but you have to type your function to the FunctionComponent (StatelessComponent in @types/react before version 16.7.2) interface so that TypeScript knows about defaultProps on the function:

interface PageProps {
  foo?: string;
  bar: number;
}

const PageComponent: FunctionComponent<PageProps> = (props) => {
  return (
    <span>Hello, {props.foo}, {props.bar}</span>
  );
};

PageComponent.defaultProps = {
  foo: "default"
};

Note that you don't have to use Partial<PageProps> anywhere because FunctionComponent.defaultProps is already specified as a partial in TS 2.1+.

Another nice alternative (this is what I use) is to destructure your props parameters and assign default values directly:

const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
  return (
    <span>Hello, {foo}, {bar}</span>
  );
};

Then you don't need the defaultProps at all! Be aware that if you do provide defaultProps on a function component it will take precedence over default parameter values, because React will always explicitly pass the defaultProps values (so the parameters are never undefined, thus the default parameter is never used.) So you'd use one or the other, not both.

Answer from Aaron Beall on Stack Overflow
Top answer
1 of 12
431

Default props with class component

Using static defaultProps is correct. You should also be using interfaces, not classes, for the props and state.

Update 2018/12/1: TypeScript has improved the type-checking related to defaultProps over time. Read on for latest and greatest usage down to older usages and issues.

For TypeScript 3.0 and up

TypeScript specifically added support for defaultProps to make type-checking work how you'd expect. Example:

interface PageProps {
  foo: string;
  bar: string;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, { this.props.foo.toUpperCase() }</span>
        );
    }
}

Which can be rendered and compile without passing a foo attribute:

<PageComponent bar={ "hello" } />

Note that:

  • foo is not marked optional (ie foo?: string) even though it's not required as a JSX attribute. Marking as optional would mean that it could be undefined, but in fact it never will be undefined because defaultProps provides a default value. Think of it similar to how you can mark a function parameter optional, or with a default value, but not both, yet both mean the call doesn't need to specify a value. TypeScript 3.0+ treats defaultProps in a similar way, which is really cool for React users!
  • The defaultProps has no explicit type annotation. Its type is inferred and used by the compiler to determine which JSX attributes are required. You could use defaultProps: Pick<PageProps, "foo"> to ensure defaultProps matches a sub-set of PageProps. More on this caveat is explained here.
  • This requires @types/react version 16.4.11 to work properly.

For TypeScript 2.1 until 3.0

Before TypeScript 3.0 implemented compiler support for defaultProps you could still make use of it, and it worked 100% with React at runtime, but since TypeScript only considered props when checking for JSX attributes you'd have to mark props that have defaults as optional with ?. Example:

interface PageProps {
    foo?: string;
    bar: number;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps: Partial<PageProps> = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, world</span>
        );
    }
}

Note that:

  • It's a good idea to annotate defaultProps with Partial<> so that it type-checks against your props, but you don't have to supply every required property with a default value, which makes no sense since required properties should never need a default.
  • When using strictNullChecks the value of this.props.foo will be possibly undefined and require a non-null assertion (ie this.props.foo!) or type-guard (ie if (this.props.foo) ...) to remove undefined. This is annoying since the default prop value means it actually will never be undefined, but TS didn't understand this flow. That's one of the main reasons TS 3.0 added explicit support for defaultProps.

Before TypeScript 2.1

This works the same but you don't have Partial types, so just omit Partial<> and either supply default values for all required props (even though those defaults will never be used) or omit the explicit type annotation completely.

Default props with Functional Components

You can use defaultProps on function components as well, but you have to type your function to the FunctionComponent (StatelessComponent in @types/react before version 16.7.2) interface so that TypeScript knows about defaultProps on the function:

interface PageProps {
  foo?: string;
  bar: number;
}

const PageComponent: FunctionComponent<PageProps> = (props) => {
  return (
    <span>Hello, {props.foo}, {props.bar}</span>
  );
};

PageComponent.defaultProps = {
  foo: "default"
};

Note that you don't have to use Partial<PageProps> anywhere because FunctionComponent.defaultProps is already specified as a partial in TS 2.1+.

Another nice alternative (this is what I use) is to destructure your props parameters and assign default values directly:

const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
  return (
    <span>Hello, {foo}, {bar}</span>
  );
};

Then you don't need the defaultProps at all! Be aware that if you do provide defaultProps on a function component it will take precedence over default parameter values, because React will always explicitly pass the defaultProps values (so the parameters are never undefined, thus the default parameter is never used.) So you'd use one or the other, not both.

2 of 12
23

With Typescript 2.1+, use Partial < T > instead of making your interface properties optional.

export interface Props {
    obj: Model,
    a: boolean
    b: boolean
}

public static defaultProps: Partial<Props> = {
    a: true
};
🌐
GitHub
github.com › microsoft › TypeScript › issues › 54979
Interface Default Values · Issue #54979 · microsoft/TypeScript
July 12, 2023 - ... The best syntax would be , This suggests x default value is "y" and when x value is not given "y" is used · export interface AccordionColors { x : string = "y" } Components in React , have a lot of parameters and a lot of them need to be ...
Author   wakaztahir
Discussions

Typescript interface default values - Stack Overflow
I have the following interface in TypeScript: interface IX { a: string, b: any, c: AnotherType } I declare a variable of that type and I initialize all the properties let x: IX = { ... More on stackoverflow.com
🌐 stackoverflow.com
Defaulting Unspecified Interface Properties to Null in TypeScript - Ask a Question - TestMu AI Community
I have the following TypeScript interface: interface IX { a: string; b: any; c: AnotherType; } I declare a variable of this type and initialize all the properties with default values: let x: IX = { a: … More on community.testmuai.com
🌐 community.testmuai.com
0
July 25, 2024
Default value for interface property?

If you have Object.assign, or a polyfill for it, or something similar like $.extend in jQuery, then you can do:

const settings = Object.assign({}, defaults, options);

The es6.d.ts declaration looks like this:

assign<T, U>(target: T, source: U): T & U;
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
assign(target: any, ...sources: any[]): any;

i.e. strongly-typed overloads up to 4 arguments. So you should get back an object whose type is the intersection of the arguments you passed in.

In short, this will perform defaulting for multiple properties in one go.

More on reddit.com
🌐 r/typescript
2
2
March 22, 2016
Why are props not marked as readonly by default in TypeScript?
The reason why props are not marked as readonly by default in TypeScript is because TypeScript does not enforce immutability by default. In the context of React, props are meant to be immutable. This is a fundamental aspect of how React works, and it's a best practice that's enforced by the React runtime, not by TypeScript. So, I guess the point I'm trying to make is that TypeScript wasn't made to strongly compliment React and as such they have their own rulebook when it comes to principles. Whether you agree or not is up to you, but if they'd change this spec now, it would likely be a breaking change. More on reddit.com
🌐 r/reactjs
28
39
July 29, 2023
🌐
DEV Community
dev.to › qpwo › documenting-default-interface-values-in-typescript-or-trying-to-3b01
Documenting default interface values in typescript, or trying to... - DEV Community
May 9, 2022 - Surely the declaration file will point your numerous future library users to this class, and if they examine it with a careful eye, they will be able to determine the default values of your optional arguments. You hold your breath, run tsc, and open index.d.ts · interface PartialOptions { id: string excellence: number color?: string isAdmin?: boolean } export declare function addUser(options: PartialOptions): void export {}
🌐
React TypeScript Cheatsheets
react-typescript-cheatsheet.netlify.app › typing defaultprops
Typing defaultProps | React TypeScript Cheatsheets
interface IMyComponentProps { firstProp?: string; secondProp: IPerson[]; } export class MyComponent extends React.Component<IMyComponentProps> { public static defaultProps: Partial<IMyComponentProps> = { firstProp: "default", }; } The problem with this approach is it causes complex issues with the type inference working with React.JSX.LibraryManagedAttributes.
🌐
Tim Mousk
timmousk.com › blog › typescript-interface-default-value
How To Set Up A TypeScript Interface Default Value? – Tim Mouskhelichvili
March 27, 2023 - An interface works at compile time and is used for type checking. The TypeScript compiler doesn't covert interfaces to JavaScript. Since interfaces only work at compile-time, they cannot be used to set up runtime default values.
🌐
Medium
chrisfrewin.medium.com › react-with-typescript-optional-props-with-default-values-cf4c8370659f
React with TypeScript: Optional Props with Default Values | by Chris Frewin | Medium
October 10, 2021 - When using TypeScript with React, it’s easy enough to define optional props. With your props interface, you simply apply the optional parameter symbol ?: interface IMyComponentRequiredProps { someRequiredProp: string; someOptionalProp?: string; } But what if we want default values for our optional props in the case when they are not specified?
🌐
DEV Community
dev.to › bytebodger › default-props-in-react-typescript-2o5o
Default Props in React/TypeScript - DEV Community
July 29, 2020 - React knows which values are required and which ones are optional. TypeScript understands the type associated with each argument. But IMHO, this approach still has... problems. The full list of properties is spelled out twice - once in the interface, and once in the function signature.
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript interface default value
TypeScript Interface Default Value | Learn the Syntax and Examples
April 18, 2023 - Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more. ... To declare an interface, an interface keyword is used. Below syntax shows how to declare an interface in TypeScript− ... Now within this declaration syntax of interface different objects can be defined whose default values are mentioned for example as,
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Webdevtutor
webdevtutor.net › blog › typescript-react-interface-props-default-value
How to Set Default Values for Props in TypeScript with React Interfaces
For instance, consider a simple ... {age}</p> </div> ); }; To set default values for props in TypeScript, you can leverage optional properties in interfaces combined with the Partial utility type....
🌐
YouTube
youtube.com › watch
How to Define Default Values for Function Types in TypeScript Interfaces for React Context - YouTube
A comprehensive guide on setting default values for function types in TypeScript interfaces with React useContext hooks, tailored for beginners.---This video...
Published   April 4, 2025
Views   0
🌐
TestMu AI Community
community.testmuai.com › ask a question
Defaulting Unspecified Interface Properties to Null in TypeScript - Ask a Question - TestMu AI Community
July 25, 2024 - I have the following TypeScript interface: interface IX { a: string; b: any; c: AnotherType; } I declare a variable of this type and initialize all the properties with default values: let x: IX = { a: 'abc', b: null, c: null }; Later, I assign actual values to these properties in an init function: x.a = 'xyz'; x.b = 123; x.c = new AnotherType(); I don’t like having to specify default null values for each property when declaring the object, especially since they will...
🌐
Chrisfrew
chrisfrew.in › blog › react-with-typescript-optional-props-with-default-values
React with TypeScript: Optional Props with Default Values
October 10, 2021 - When using TypeScript with React, it's easy enough to define optional props. With your props interface, you simply apply the optional parameter symbol ?: interface IMyComponentRequiredProps { someRequiredProp: string; someOptionalProp?: string; } But what if we want default values for our optional props in the case when they are not specified?
🌐
Technical Feeder
technicalfeeder.com › 2022 › 08 › typescript-how-to-set-a-default-value-with-interface
TypeScript How to set a default value with Interface | Technical Feeder
October 26, 2022 - This page shows 3 ways to set default values to an interface. Using Spread Operator is an easy way. You can also define the default values in a function. An advanced way is to create a class for it.
🌐
Quora
quora.com › What-are-the-default-values-of-a-Typescript-Interface
What are the default values of a Typescript Interface? - Quora
Answer (1 of 2): An interface describes the shape of data and isn’t data itself. If you compile a .ts file that only has an interface in it, it won’t generate any code. So, interfaces have no data and no default value.
🌐
LogRocket
blog.logrocket.com › home › understanding and using interfaces in typescript
Understanding and using interfaces in TypeScript - LogRocket Blog
October 17, 2024 - While interfaces in TypeScript are excellent for defining the shape of objects, they cannot directly specify default values for properties. However, we can use a combination of optional properties and factory functions to achieve a similar effect.
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-interface-default-values
How to set up TypeScript interface Default values | bobbyhadz
February 26, 2024 - When using this approach, we can ... if it gets called with no parameters. It should be noted that you can't explicitly set default values in an interface, because interfaces and types get removed during compilati...
🌐
Medium
medium.com › @rare › setting-default-values-in-typescript-ac7f31482996
Setting Default Values in TypeScript | by rare. | Medium
May 14, 2024 - We use object destructuring with default values directly in the function parameter list. This method allows each property to have a default value, which is used if the corresponding property is not provided in the argument object.