13

I ran into this weird case. I declare a conditional type. For the same extends constraint, a type alias satisfies it, while a structurally identical interface doesn't.

I'm so lost, why the difference? Check the playground.

interface Constraint {
  [key: string]: string | number | boolean
}

type ATypeAlias = {
  str: string
  num: number
  bool: boolean
}

interface SameInterface {
  str: string
  num: number
  bool: boolean
}

type expectToBeTrue = ATypeAlias extends Constraint ? true : false

// Wat???
type butWhyAmIFalse = SameInterface extends Constraint ? true : false

1 Answer 1

15

You've run into a known issue, microsoft/TypeScript#15300 whereby implicit index signatures are inferred for type aliases but not for interfaces. This is one of those few places where type aliases and interfaces differ in type analysis. According to @RyanCavanaugh (Development lead for the TypeScript team at Microsoft), this is by design:

Just to fill people in, this behavior is currently by design. Because interfaces can be augmented by additional declarations but type aliases can't, it's "safer" (heavy quotes on that one) to infer an implicit index signature for type aliases than for interfaces.

For a while this issue was kept open as a suggestion to change the behavior, but it was ultimately declined with the comment:

Changing the behavior at this point would honestly be an incredibly disruptive breaking change without much concrete upside. For clarity, I'm going to close and lock this - interfaces should declare an explicit index signature if they intend to be indexed.

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

1 Comment

Thanks for the reply and links. I don't see why it's "safer" though :-/

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.