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 '"" | "," | " " | "."'.
4
  • options.thousandSeparator should be const if you want to assign it to type '' | ',' | ' ' | '.' Commented Aug 13, 2020 at 9:17
  • 2
    TLDR: use const options = { thousandSeparator: ',' as const }; so ',' is actually of type ',' and not widened to type 'string'. Commented Aug 13, 2020 at 9: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. Commented May 29, 2022 at 9: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. Commented May 29, 2022 at 9:09

1 Answer 1

3

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,
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.