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

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.