Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for typescript type alias

Can typescript type alias support default arguments? For instance:

export type SomeType = {
    typename: string;
    strength: number;
    radius: number;
    some_func: Function;
    some_other_stat: number = 8; // <-- This doesn't work
}

The error is A type literal property cannot have an initializer.

I can't find documentation relating to this - type keyword is very obscure behind everything else that is also named type. Is there anything I can do to have default argument value for type in typescript?

like image 647
Rocky Li Avatar asked May 18 '20 04:05

Rocky Li


People also ask

Can a type have a default value TypeScript?

TypeScript has two special types, null and undefined , that have the values null and undefined respectively. We mentioned these briefly in the Basic Types section. By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values of every type.

What is type alias in TypeScript?

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.

What is the default value of number type in TypeScript?

We didn't have to explicitly type the by parameter, because TypeScript can infer its type based on the default value. If the multiply function is invoked without a value for the by parameter, or is explicitly passed undefined , the argument will be replaced with the default value of 10 .

How do I give a default value to a TypeScript interface?

To set default values for an interface in TypeScript, create an initializer function, which defines the default values for the type and use the spread syntax (...) to override the defaults with user-provided values. Copied!


2 Answers

You cannot add default values directly to a type declaration.

You can do something like this instead:

// Declare the type
export type SomeType = {
    typename: string;
    strength: number;
    radius: number;
    some_func: Function;
    some_other_stat: number;
}

// Create an object with all the necessary defaults
const defaultSomeType = {
    some_other_stat: 8
}

// Inject default values into your variable using spread operator.
const someTypeVariable: SomeType = {
  ...defaultSomeType,
  typename: 'name',
  strength: 5,
  radius: 2,
  some_func: () => {}
}
like image 109
Karthick Vinod Avatar answered Oct 24 '22 08:10

Karthick Vinod


Type does not exist in runtime, so a default value makes no sense. If you want to have a default default, you must use something that exists in runtime, such as a class or a factory function

like image 24
HTN Avatar answered Oct 24 '22 09:10

HTN