0

I have the following type defined in typescript

export type Unit =
    | 'year'
    | 'month'
    | 'day'
    | 'hour'
    | 'minute'
    | 'second'
    | 'millisecond'

Is there a way to check a string if that string matches any of the above types using typescript?


const x = 'abc'

x "typeOf" Unit => false?

EDIT: Found anwser, have marked question as duplicate

Checking validity of string literal union type at runtime?

Han Che
  • 8,239
  • 19
  • 70
  • 116
  • check in runtime? – Nikita Madeev Jun 23 '20 at 07:14
  • yes that would be my goal – Han Che Jun 23 '20 at 07:17
  • 1
    then you should look away [enum](https://www.typescriptlang.org/docs/handbook/enums.html), because [types are stripped away at compile-time and do not exist at runtime](https://stackoverflow.com/questions/44078205/how-to-check-the-object-type-on-runtime-in-typescript) – Nikita Madeev Jun 23 '20 at 07:18
  • @HanChe do you control creation of type `Unit` or it comes from 3rd party? – Aleksey L. Jun 23 '20 at 07:27
  • Found the anwser in the post https://stackoverflow.com/questions/36836011/checking-validity-of-string-literal-union-type-at-runtime – Han Che Jun 23 '20 at 07:29
  • 2
    If the definition of the type is in your hands - you can create array of valid unit values, then create a `Unit` type from it – Aleksey L. Jun 23 '20 at 07:32
  • 2
    https://www.typescriptlang.org/play/index.html#code/MYewdgzgLgBAqgOQJIBUDKMC8MDaByATwFMBDAJzwBoY8BbcKACypoBMSCW9GQBXC6nQCWYXlCJcIRUGFZdaQgDaKhUmXIC6MEhBgzoAbgCwAKFNQCAByLwwQ2NgvWQAM3jJ0OUbQBGRMhoGMAD0wTAARMTk4TAAPhH0YEwx8eHsBCkRPPyZ4Qqi4rlq4Ky5Csqq0iXhpqb6sKpwdg4wABS8AFzaYAQAlF28MKq29lgAfO6oaAB0IqxEAB4A8i7tvTAAhJjYALQAjAZAA – Aleksey L. Jun 23 '20 at 07:34
  • 1
    Oh, did not think about it, nice solution :) – Nikita Madeev Jun 23 '20 at 07:37
  • @AlekseyL. Cool solution! Could you explain quickly the `typeof UNITS[number]`? How does typeof convert array to a type and what does the `[number]` do? – Han Che Jun 24 '20 at 06:05
  • 1
    @HanChe `typeof` operator allows to query the type of variable (value). so `typeof UNITS` is tuple `['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond']`. Now `[number]` part is "index access operator" at type level - returns type of tuple/array member (which is union of all valid tuple members) https://stackoverflow.com/questions/46376468/how-to-get-type-of-array-items/46387055#46387055 – Aleksey L. Jun 24 '20 at 06:09
  • https://stackoverflow.com/a/66820587/3333878 – abitcode Mar 28 '21 at 18:45

0 Answers0