0

i have this function that randomize 3 strings, but when i try to return the value, i got this error

Type 'string' is not assignable to type '"DAY" | "GTD" | "GTC"'

my function:

export const randomizeTimeinforce = (): 'DAY' | 'GTD' | 'GTC' => {
  const timeinforce = ['DAY', 'GTD', 'GTC'];
  return timeinforce[Math.floor(Math.random() * 3)];
};


export class MyCoolClass {
  public timeinforce: 'DAY' | 'GTD' | 'GTC' = randomizeTimeinforce();
}

1 Answer 1

3

You'll need to add a so called const assertion to avoid TS interpreting your timeinforce array as string[]. This latter (default) behavior is also called type widening and is something you want to avoid here...

export const randomizeTimeinforce = () => {
  const timeinforce = <const>['DAY', 'GTD', 'GTC'];
  return timeinforce[Math.floor(Math.random() * 3)];
};


export class MyCoolClass {
  public timeinforce = randomizeTimeinforce();
}

TypeScript playground

2
  • works, but i got this error in my console: error TS2304: Cannot find name 'const'
    – Igor
    Apr 1, 2020 at 22:00
  • @Igor you must be using an old version of TS - const assertions were added in 3.4 (typescriptlang.org/docs/handbook/release-notes/…) - I've also added a playground link, where you can try it out w/ different TS versions...
    – toxi
    Apr 1, 2020 at 22:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.