export type Fruit = "Orange" | "Apple" | "Banana"
const myString = "Banana";
const myFruit: Fruit = myString;
...it works. Why? Because the actual type of myString
in this example is "Banana"
. Yes, "Banana"
is the type. It is extends String
so it's assignable to String
. Additionally, a type extends a Union Type when it extends any of its components. In this case, "Banana"
, the type, extends "Orange" | "Apple" | "Banana"
because it extends one of its components. Hence, "Banana"
is assignable to "Orange" | "Apple" | "Banana"
or Fruit
.
–
There are several situations that will give you this particular error. In the case of the OP there was a value defined explicitly as a string. So I have to assume that maybe this came from a dropdown, or web service or raw JSON string.
In that case a simple cast <Fruit> fruitString
or fruitString as Fruit
is the only solution (see other answers). You wouldn't ever be able to improve on this at compile time. [Edit: See my other answer about <const>
] !
However it's very easy to run into this same error when using constants in your code that aren't ever intended to be of type string. My answer focuses on that second scenario:
First of all: Why are 'magic' string constants often better than an enum?
I like the way a string constant looks vs. an enum - it's compact and 'javascripty'
Makes more sense if the component you're using already uses string constants.
Having to import an 'enum type' just to get an enumeration value can be troublesome in itself
Whatever I do I want it to be compile safe so if I add remove a valid value from the union type, or mistype it then it MUST give a compile error.
Fortunately when you define:
export type FieldErrorType = 'none' | 'missing' | 'invalid'
...you're actually defining a union of types where 'missing'
is actually a type!
I often run into the 'not assignable' error if I have a string like 'banana'
in my typescript and the compiler thinks I meant it as a string, whereas I really wanted it to be of type banana
. How smart the compiler is able to be will depend on the structure of your code.
Here's an example of when I got this error today:
// this gives me the error 'string is not assignable to type FieldErrorType'
fieldErrors: [ { fieldName: 'number', error: 'invalid' } ]
As soon as I found out that 'invalid'
or 'banana'
could be either a type or a string I realized I could just assert a string into that type. Essentially cast it to itself, and tell the compiler no I don't want this to be a string!
// so this gives no error, and I don't need to import the union type too
fieldErrors: [ { fieldName: 'number', error: <'invalid'> 'invalid' } ]
So what's wrong with just 'casting' to FieldErrorType
(or Fruit
)
// why not do this?
fieldErrors: [ { fieldName: 'number', error: <FieldErrorType> 'invalid' } ]
It's not compile time safe:
<FieldErrorType> 'invalidddd'; // COMPILER ALLOWS THIS - NOT GOOD!
<FieldErrorType> 'dog'; // COMPILER ALLOWS THIS - NOT GOOD!
'dog' as FieldErrorType; // COMPILER ALLOWS THIS - NOT GOOD!
Why? This is typescript so <FieldErrorType>
is an assertion and you are telling the compiler a dog is a FieldErrorType! And the compiler will allow it!
BUT if you do the following, then the compiler will convert the string to a type
<'invalid'> 'invalid'; // THIS IS OK - GOOD
<'banana'> 'banana'; // THIS IS OK - GOOD
<'invalid'> 'invalidddd'; // ERROR - GOOD
<'dog'> 'dog'; // ERROR - GOOD
Just watch out for stupid typos like this:
<'banana'> 'banan'; // PROBABLY WILL BECOME RUNTIME ERROR - YOUR OWN FAULT!
Another way to solve the problem is by casting the parent object:
My definitions were as follows:
export type FieldName = 'number' | 'expirationDate' | 'cvv';
export type FieldError = 'none' | 'missing' | 'invalid';
export type FieldErrorType = { field: FieldName, error: FieldError };
Let's say we get an error with this (the string not assignable error):
fieldErrors: [ { field: 'number', error: 'invalid' } ]
We can 'assert' the whole object as a FieldErrorType
like this:
fieldErrors: [ <FieldErrorType> { field: 'number', error: 'invalid' } ]
Then we avoid having to do <'invalid'> 'invalid'
.
But what about typos? Doesn't <FieldErrorType>
just assert whatever is on the right to be of that type. Not in this case - fortunately the compiler WILL complain if you do this, because it's clever enough to know it's impossible:
fieldErrors: [ <FieldErrorType> { field: 'number', error: 'dog' } ]
I see this is a little old, but there might be a better solution here.
When you want a string, but you want the string to only match certain values, you can use enums.
For example:
enum Fruit {
Orange = "Orange",
Apple = "Apple",
Banana = "Banana"
let myFruit: Fruit = Fruit.Banana;
Now you'll know that no matter what, myFruit will always be the string "Banana" (Or whatever other enumerable value you choose). This is useful for many things, whether it be grouping similar values like this, or mapping user-friendly values to machine-friendly values, all while enforcing and restricting the values the compiler will allow.
–
–
All the above answers are valid, however, there are some cases that the String Literal Type is part of another complex type. Consider the following example:
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small',
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
// Here you will get the following error:
// Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
['large', 'small'].forEach(size => (
useToolbarTheme({ size })
You have multiple solutions to fix this. Each solution is valid and has its own use cases.
1) The first solution is to define a type for the size and export it from the foo.ts. This is good if when you need to work with the size parameter by its own. For example, you have a function that accepts or returns a parameter of type size and you want to type it.
// in foo.ts
export type ToolbarThemeSize = 'large' | 'small';
export type ToolbarTheme = {
size: ToolbarThemeSize
// in bar.ts
import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
function getToolbarSize(): ToolbarThemeSize {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size: size as ToolbarThemeSize })
2) The second option is to just cast it to the type ToolbarTheme. In this case, you don't need to expose the internal of ToolbarTheme if you don't need.
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small'
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size } as ToolbarTheme)
In arrays with spreading this error can still be thrown a bit misleadingly:
export type Fruit = "Orange" | "Apple" | "Banana"
export type FruitArray = Fruit[];
const someFruits= ["Banana"];
const workingFruits: FruitArray = ["Orange", "Apple"]; // Works
// Even orange and apple show: Type 'string' is not assignable to type Fruit
const brokenAllFruits: FruitArray = [...someFruits, "Orange", "Apple"];
// As const is needed in the spread array
const someConstFruits= ["Banana" as const];
const workingAllFruits: FruitArray = [...someConstFruits, "Orange", "Apple"]; // Works
I had a similar issue when passing props to a React Component.
Reason: My type inference on myArray wasn't working correctly
https://codesandbox.io/s/type-string-issue-fixed-z9jth?file=/src/App.tsx
Special thanks to Brady from Reactiflux for helping with this issue.
If you're casting to a dropdownvalue[]
when mocking data for example, compose it as an array of objects with value and display properties.
example:
[{'value': 'test1', 'display1': 'test display'},{'value': 'test2', 'display': 'test display2'},]
This question was tagged Angular even though it's not really anything to do with Angular. However there is (at least) one Angular specific case where you may get this error unexpectedly.
If you have disabled strictNullInputTypes
If you use a literal type such as Fruit
as an @Input()
You try to pass 'Orange'
to an input and it gets interpreted as a string.
This will be fixed in Angular 13.1.
https://github.com/angular/angular/pull/38305
If you are working with classes you could do e.g. one of the following:
Example model:
type Fruit = 'Apple' | 'Banana';
interface ClassWithFruit {
fruit: Fruit;
Class that implements model, here are three options:
class MyClass implements ClassWithFruit {
// option 1
fruit = 'Apple' as const;
// option 2
fruit = <const>'Apple';
// option 3
readonly fruit = 'Apple';
I was facing the same issue, I made below changes and the issue got resolved.
Open watchQueryOptions.d.ts file
\apollo-client\core\watchQueryOptions.d.ts
Change the query type any instead of DocumentNode, Same for mutation
Before:
export interface QueryBaseOptions<TVariables = OperationVariables> {
query: **DocumentNode**;
After:
export interface QueryBaseOptions<TVariables = OperationVariables> {
query: **any**;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.