[SOLVED] Argument of type {stringVariable} not assignable to object of type {string literal}

Issue

I have the following code, which takes an options parameter:

const getCat = function (options: { format: "decimal" }) {
    return null
}
const options = { format: "decimal" }
const cat = getCat(options)

However, the const cat = getCat(options) runs into an error:

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

How can I cast my options to be of the type TypeScript is looking for?

Solution

You have 2 choices:

  1. Send the options right to the function:

    const cat = getCat({ format: "decimal" })
    
  2. Declare a type and have options be that type

    type MyType = { format: "decimal" }
    const options: MyType = { format: "decimal" }
    const cat = getCat(options)
    

Answered By – Patrick Collins

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *