ErikE
ErikE

Reputation: 50201

Force type error when string doesn't match key of object

In TypeScript 4.4.3, how can I cause the incorrect string 'c' below to show a type error, (because it is not one of the keys of the object that is the first parameter of the doSomething method)?

const doSomething = ({ a, b }: { a: number, b: string }): boolean => {
  return a === 1 || b === 'secret'
}

type SomethingParameterName = keyof Parameters<typeof doSomething>[0]

const orderedParameterNames = [
  'b', 'c', 'a' // why no type error for 'c'?
] as SomethingParameterName[]

See this code at TypeScript Playground.

I played around with const a bit, and directly tried 'c' as SomethingParameterName but that also gives no type error. In this case, I don't have an easy way to get the list of keys from another source than the function itself.

Upvotes: 1

Views: 363

Answers (1)

ErikE
ErikE

Reputation: 50201

The TypeScript construct as TypeName is essentially a type-cast. Because the base type of a union of const strings is string, TypeScript accepts this type-cast as a compatible type assertion. To get the expected error, define the type of the variable orderedParameterNames, instead of casting the value that is being assigned to it:

const orderedParameterNames: SomethingParameterName[] = [
  'b', 'c', 'a'
]

This will now give an error on 'c':

TS2322: Type '"c"' is not assignable to type '"a" | "b".

Upvotes: 1

Related Questions