I want to create custom type in typescript like this:
color?: 'textPrimary' | 'textSecondary' | string;
so we have some default value and also other strings.
but typescript convert it to string | undefined
How can I achieve this?
I want to create custom type in typescript like this:
color?: 'textPrimary' | 'textSecondary' | string;
so we have some default value and also other strings.
but typescript convert it to string | undefined
How can I achieve this?
As Ben commented, there's no need to define a type for those extra values you want to fall back, as they are also of type string
.
In any case, you may be interested in using enums so you can store those 'default values' you are trying to save. This is helpful for the future of your code, so if there's a need to change those values to another default string, you can only change the enum
and not go to each hardcoded string and changing them one by one.
Do something like this:
enum defaultClasses {
primary = 'textPrimary',
secondary = 'textSecondary'
}
class baseProp {
color?: defaultClasses | string
}
const prop = new baseProp()
prop.color = defaultClasses.primary
console.log(prop.color) # 'textPrimary'
That doesn't make sense. A 'type' is simply a description of all the possible values that a variable, argument or object property can take.
The type 'textPrimary' | 'textSecondary'
means 'this variable can only take the value 'textPrimary' or 'textSecondary'.
The type string
represents 'all the legal values of a string in JavaScript' - which includes 'textPrimary' and 'textSecondary', so these more specific types are redundant. Hence why TypeScript did the right thing and eliminated them.