DEV Community

Discussion on: TypeScript is wasting my time

Collapse
 
florianrappl profile image
Florian Rappl

I don't want to go into all of your issues. So I stop at the first one since no one mentioned this:

function formatNumber(value: number, lang: string = 'en') {
  const options = {
    notation: 'compact' as const,
    maximumFractionDigits: 1,
  };
  const formatter = Intl.NumberFormat(lang, options);
  return formatter.format(value);
}

Enter fullscreen mode Exit fullscreen mode

Solves your problem here. By default, TS makes / types these objects loosely, as such at it sees

interface TempInterface {
  notation: string;
  maximumFractionDigits: number;
}
Enter fullscreen mode Exit fullscreen mode

which makes sense as nothing prevents you to write options.notation = 'foo'. I think you fall into the trap of thinking that const means immutable, but it rather means "cannot be reassigned".

The alternative to help TypeScript here with the as const is to just tell it the right interface in the assignment.