0

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?

7
  • 2
    Directly pass it into the call: getCat({ format: "decimal" }) or declare an actual type for the parameter. Commented Mar 15, 2022 at 16:46
  • 1
    Why does passing it directly work? Commented Mar 15, 2022 at 16:49
  • 1
    Because then the type doesn't get widened, because there's no reference through which that value could be changed. options is infered as { format: string } unless you add as const (either to the object or the string) [related: stackoverflow.com/a/62652353/3001761]. Commented Mar 15, 2022 at 16:49
  • @PatrickCollins Because then TS knows the type is { format: "decimal" } and not just any string. If you declare a type you can also do const options: MyType = /* ... */ to get the same effect. Commented Mar 15, 2022 at 16:50
  • Well that worked splended! So typescript won't just detect the typing works? Commented Mar 15, 2022 at 16:53

1 Answer 1

0

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)
    
Sign up to request clarification or add additional context in comments.

3 Comments

You have at least 3, because there are various uses of const assertions that work too.
Could you add the third?
I explained why this happens and various options (including these two) in the post I linked to above

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.