Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript satisfies turns boolean type to literal. Is this normal?

Tags:

typescript

While other types are same, type 'boolean' become literal 'false' after satisfies "TypesSamples"


interface TypesSamples {
  str: string;
  int: number;
  arr: Array<any>;
  bool: boolean;
}

const types = {
  str: "a",
  int: 0,
  arr: [1],
  bool: false,
} satisfies TypesSamples; // satisfies here

types.str = "abc";
types.int = 1000;
types.arr = [2, 3];
types.bool = true; // Type 'true' is not assignable to type 'false'.

Is this an expected behaviour or an issue?

like image 353
RunningEgg Avatar asked Oct 22 '25 10:10

RunningEgg


1 Answers

This is the expected behavior, as described in microsoft/TypeScript#55189. The satisfies operator as implemented in microsoft/TypeScript#46827, provides a contextual type which can sometimes alter the behavior of type inference. The reason why this is specific to boolean as opposed to, say, string, is that boolean is really just a shorthand for the union type true | false. Even though it displays as a single type, it's actually a union. You can verify this by manually defining a type to be true | false and see that it displays as boolean:

type B = true | false;
//   ^? type B = boolean

So true when evaluated contextually by true | false is kept as true, as opposed to "a" when evaluated contextually by string in a satisfies expression, is still widened to string as usual.

That's as close as I can get to an "official" answer, anyway, given the details of microsoft/TypeScript#55189. It is unfortunate that the pull request in microsoft/TypeScript#46827 does not go into any detail in its description about how exactly it's supposed to work. There are other parts of TypeScript where providing a string/number context for a literal will result in a literal type, and that's not happening here, except for boolean. The boolean type differs from the others by virtue of it being an explicit union, so it's not too surprising that its behavior would differ, but whether or not this is truly intentional as opposed to just an implementation artifact is impossible for me to say with any certainty.

Playground link to code

like image 196
jcalz Avatar answered Oct 24 '25 08:10

jcalz