1

Can't understand why if I do this :

export const SET_EXPENSE = 'SET_EXPENSE';
export interface SetExpenseAction {
      type: typeof SET_EXPENSE;
      expenses: Expense[];
}

when I create the interface I need to give the type only as SET_EXPENSE. typeof(SET_EXPENSE) is string, so why it becomes a values here and limits the type only to that string?

MD10
  • 1,313
  • 3
  • 12
  • 35
  • 5
    There are two `typeof` operators; the JavaScript `typeof` which exists at runtime, and will produce the string `"string"` when you use it on `SET_EXPENSE`, and the TypeScript type query operator `typeof` which only exists in the type system and will produce the *type* of `SET_EXPENSE` as seen by the type system, which is the [string literal type](http://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types) `"SET_EXPENSE"`. See [this explanation](https://stackoverflow.com/a/50396312/2887218) for more info. – jcalz May 05 '20 at 21:18
  • thanks for the reply, but I still donn't get when typof is used as a value and where it use a type, and when it is used as a js operator.If you could provide another explantion I would be grateful – MD10 May 05 '20 at 21:40

1 Answers1

1

The inferred type of SET_EXPENSE is the string literal 'SET_EXPENSE'. TypeScript won't even allow you to compare it to a different string;

if (SET_EXPENSE === "other string") {...}

Gets you this error:

This condition will always return 'false' since the types '"SET_EXPENSE"' and '"other string"' have no overlap.

Now if you set the type yourself, to string. It will work as you expect.

export const SET_EXPENSE: string = 'SET_EXPENSE'
dovidweisz
  • 1,215
  • 13
  • 24
  • This is all true, but I'd just note that wile using `const SET_EXPENSE: string = ...` is valid, its subtly incorrect. The `SET_EXPENSE` variable cannot be any string, it can only be the specific string `"SET_EXPENSE"`. OP should not override the inferred literal type, instead if he really needs it to be `string`, he should declare it with `let` instead of `const`. – CRice May 05 '20 at 22:39
  • My question is why it behaves like that and the vatiable SET_EXPENSE cannot be something else – MD10 May 06 '20 at 07:38
  • @crice You're absolutely right, I was just answering the question as it was asked. I think it was useful still. – dovidweisz May 06 '20 at 23:03