2

In my class I have a property:

thousandSeparator: '' | ',' | ' ' | '.';

and want to set it by:

const options = {
  thousandSeparator: ','
};

when setting this I get the error

 Types of property 'thousandSeparator' are incompatible.
 Type 'string' is not assignable to type '"" | "," | " " | "."'.
daniel
  • 34,281
  • 39
  • 104
  • 158
  • `options.thousandSeparator` should be const if you want to assign it to type `'' | ',' | ' ' | '.'` – Rafał Figura Aug 13 '20 at 09:17
  • 2
    TLDR: use `const options = { thousandSeparator: ',' as const };` so `','` is actually of type `','` and not widened to type `'string'`. – sloth Aug 13 '20 at 09:17
  • Why is this question being labelled a duplicate? It is not. The linked question involves a variable with a type string and another variable with a type of a set of string values and attempting to set one variable to the other. This question is about defining a property on an object with a set of string values. – Greg May 29 '22 at 09:03
  • The code in tsc playground link is the correct answer for the response below, not what is shown in the response. The problem is that you need to define `options` with a property `thousandSeparator: '' | ',' | ' ' | '.';`, as represented in the tsc link by `type optionsType = { thousandSeparator : '' | ',' | ' ' | '.'; };` and then `const options:optionsType = { thousandSeparator: ',' };` Above, you've defined a variable, not an object property. – Greg May 29 '22 at 09:09

1 Answers1

2

Your code works fine in the tsc playground

If there is more to your code, such as defining the string elsewhere before setting it to the variable, you will have to cast it, like so:

type thousandSeparator = '' | ',' | ' ' | '.';

const options = {
  thousandSeparator: ',' as thousandSeparator,
};
Luke Storry
  • 6,032
  • 1
  • 9
  • 22