Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Why type alias satisfies a constraint but same interface doesn't?

Tags:

typescript

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
like image 571
hackape Avatar asked Apr 23 '19 15:04

hackape


1 Answers

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. But we'll consider doing it for interfaces as well if that seems to make sense. [emphasis added]

Okay, it's currently by design but the GitHub issue's status (as of 2019-04-23) is "suggestion" and "in discussion". So if you want to see this changed, you might want to go there and give the issue a 👍 or describe your use case if it's particularly compelling.

Hope that helps; good luck!

like image 114
jcalz Avatar answered Jan 04 '23 01:01

jcalz