3

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';
}
Gil Epshtain
  • 8,670
  • 7
  • 63
  • 89
  • 1
    Possible duplicate of [How to require a specific string in TypeScript interface](https://stackoverflow.com/questions/26855423/how-to-require-a-specific-string-in-typescript-interface) – Heretic Monkey Sep 23 '19 at 13:03

2 Answers2

8

You can define it as:

type DayOfWeek = 'Sun' | 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri' | 'Sat';

function setDay(day: DayOfWeek) { ... }

Andrei Tătar
  • 7,872
  • 19
  • 37
0

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.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
matreurai
  • 147
  • 12