Beau Smith
Beau Smith

Reputation: 34367

In Typescript, how to use a string literal type in an interface?

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

Upvotes: 2

Views: 2483

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25850

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.

Upvotes: 1

Related Questions