2

The duplicate issue is solving a slightly different issue. This one is specific to using a type within an interface.


I'd like to use a string literal type in an interface. I'm sure that I'm a small change away from the answer to this.

Below is a simplified example of my code which shows the error.

What do I need to change to get barFunction(baz) to not have the below Typescript error?

// foo.ts

type Name = 'a' | 'b'
interface Bar {
  x: Name
}

const n: Name = 'a'

const barFunction = (bar: Bar) => console.log(bar)

barFunction({ x: 'a' })

const baz = { x: 'a' }
barFunction(baz) // <-- error here

Error Message

Argument of type '{ x: string; }' is not assignable to parameter of type 'Bar'.  
  Types of property 'x' are incompatible.  
    Type 'string' is not assignable to type '"a"'.  

Screenshot of error message:

Error Message

Beau Smith
  • 33,433
  • 13
  • 94
  • 101

1 Answers1

1

What do I need to change to get barFunction(baz) to not have the below Typescript error?

There is nothing you can do with barFunction. The problem is not there. It's in the fact your definition for baz got widened.

In order to mitigate it, use an explicit type definition:

const baz: Bar = { x: 'a' }

…or less ideal, but also a solution:

barFunction(baz as Bar)

With TypeScript 3.4 we will be able to also do:

const baz = { x: 'a' } as const

which will make TypeScript treat 'a' as a string literal, not just any string.

Beau Smith
  • 33,433
  • 13
  • 94
  • 101
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53
  • Thank you. I also found that I can resolve error by using `barFunction(baz as Bar)`. It makes more sense to use your suggestion to cast type when creating `const` vs defining in function call so that the issue is solved in one place. – Beau Smith Mar 04 '19 at 19:45