Let say I have a variable with the following type:
let weekDay: 'Sun' | 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat';
And in different places in my project I'm using this type, so each time I write:
function setDay(day: 'Sun' | 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat') { ... }
function getDay(): 'Sun' | 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat' { ... }
How can I define this new type once, so I will not need to write it each time. I try to define an interface
but it will create an object-type with this type as one of each attributes, but this isn't what I want
interface iWeekDay {
day: 'Sun' | 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat';
}
You can define it as:
type DayOfWeek = 'Sun' | 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat';
function setDay(day: DayOfWeek) { ... }
You could also define a new type in the same file as your interface such as:
export interface IWeekDay {
day: dayType;
}
export type dayType =
| "Sun"
| "Mon"
| "Tue"
| "Wed"
| "Thu"
| "Fri"
| "Sat";
By doing so, you export a IWeekDay interface that has one param of type dayType.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.