1

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.

2
  • 1
    Because you are using as, which tells compiler you know what the type is. You should use const orderedParameterNames: SomethingParameterName[] to let the compiler check the type for you. Commented Oct 15, 2021 at 20:58
  • You're using a type assertion, which prevents the compiler from telling you it's wrong. Commented Oct 15, 2021 at 21:03

1 Answer 1

1

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".

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

Comments

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.