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?
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: () => {}
}