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?
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.
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.
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 .
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!
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: () => {}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With