Skip to content

<T extends unknown> does not narrow #38456

@asmundg

Description

@asmundg

I'm not entirely sure why you would want to extend unknown. But if you end up doing it, it seems a bit surprising that the narrowing behavior is not the same as for unknown itself.

TypeScript Version: 4.0.0-dev.20200509

Search Terms: narrow unknown

Code

function works(arg: unknown): void {
  typeof arg === "object" && !!arg && Object.keys(arg);
}

function fails<T extends unknown>(arg: T): void {
  // No overload matches this call.
  // Overload 1 of 2, '(o: {}): string[]', gave the following error.
  //   Argument of type 'T' is not assignable to parameter of type '{}'.
  //     Type 'unknown' is not assignable to type '{}'.
  // Overload 2 of 2, '(o: object): string[]', gave the following error.
  //   Argument of type 'T' is not assignable to parameter of type 'object'.
  //     Type 'unknown' is not assignable to type 'object'.
  typeof arg === "object" && !!arg && Object.keys(arg);
}

Expected behavior:

Both examples compile.

Actual behavior:

Only works compiles.

Playground Link: https://www.typescriptlang.org/play?ts=4.0.0-dev.20200509#code/GYVwdgxgLglg9mABAdzgJwNYGcAUBDNAcwC5FwMw5kwBKUgNzhgBNEBvAKEUSgE8AHAKZxgiAoUQBeaYgBEcAEYArQdFmIAZBsQBCHeM3aA8stVQAdBkG9c4mgG4OAXw4dQkWAkTA8MADZYADwAKoiCAB5QgmDMWGRgFFRgAHz4RKTBdIiMLOxciAD0BYgAcnCIcPSCaH5weKwAtnhQEAAWgnFQrTBxEHh+fub5RYhGVTV1rACMFaIATAA0iADkOHCkbE5ZWFBoMGCEANoAustLhHhVPO3ecANU+xLVaOhD3CPcAIJEIA3RULMeAJBCtgstED1EJQAXgsFgYIQwHgFH4QVByvwCHg-lE0IC+EIVptlm9CsVuNxgsCVuRKNRwZDoWI4QikSi0eUCSDlsTSSMxtVavVEHNAYsVmtSIoVNBtrtHiczogLlcuiDgHdashHmE0C80HzyYhvoRfv98dTlmCIXEmbD4YjkaieBisTjqhbCctpWYScMjZTLbSkgzbXAYSzHeyXUCvT7oH7uFyRGIiFIZPJTGpDLp9GmtKMsxYrDY0oQHM4gA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions