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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Patrick Collins
  • 5,621
  • 3
  • 26
  • 64
  • 2
    Directly pass it into the call: `getCat({ format: "decimal" })` or declare an actual type for the parameter. – VLAZ Mar 15 '22 at 16:46
  • 1
    Why does passing it directly work? – Patrick Collins Mar 15 '22 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: https://stackoverflow.com/a/62652353/3001761]. – jonrsharpe Mar 15 '22 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. – VLAZ Mar 15 '22 at 16:50
  • Well that worked splended! So typescript won't just detect the typing works? – Patrick Collins Mar 15 '22 at 16:53
  • _"typescript won't just detect the typing works?"_ - what? It _does_ detect that the typing _doesn't_ work, because `options` could get changed before `getCat` gets called - objects are mutable. If `options.format` can only have that one value, or a smaller range than `string`, you need to tell the compiler so it can help enforce that requirement. – jonrsharpe Mar 15 '22 at 16:55
  • Sorry, I meant to say "typescript won't auto convert/cast the typing for you". I see. Thanks for the info. – Patrick Collins Mar 15 '22 at 22:39

1 Answers1

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)
    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Patrick Collins
  • 5,621
  • 3
  • 26
  • 64