Search code examples
typescriptclasstyping

how to return typed value


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();
}

Solution

  • 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