Skip to content

Recursive types highlight error unless narrowed down by using as keyword #126128

@khooz

Description

@khooz

Does this issue occur when all extensions are disabled?: Yes

  • VS Code Version: 1.57.0 (user setup)
  • OS Version: Windows_NT x64 10.0.19042
  • Commit: b4c1bd0
  • Date: 2021-06-09T17:18:42.354Z
  • Electron: 12.0.9
  • Chrome: 89.0.4389.128
  • Node.js: 14.16.0
  • V8: 8.9.255.25-electron.0

Steps to Reproduce:

  1. Write a recursive interface, eg.
interface SomeType {
   key: string,
   value: string
}

interface RecursiveType {
   [x : string] : RecursiveType | SomeType
}
  1. Define a value of the type:
const test : RecursiveType = {
   testKeyOne: {
      nestedOne: {
         key: 'test',
         value: 'test'
      }
   },
   testKeyTwo: {
      nestedOne: {
         nestedTwo: {
            key: 'test',
            value: 'test'
         }
      }
   }
};
  1. Use the variable
test.testKeyOne.nestedOne.key;
/* red squiggly line stating:
Property 'nestedOne' does not exist on type 'RecursiveType | SomeType'.
  Property 'nestedOne' does not exist on type 'SomeType'.ts(2339)
*/

(test.testKeyTwo as RecursiveType).nestedOne.nestedTwo.key;
/*
red squiggly line shifts a level deeper stating:
Property 'nestedTwo' does not exist on type 'RecursiveType | SomeType'.
  Property 'nestedTwo' does not exist on type 'SomeType'.ts(2339)
*/

((test.testKeyTwo as RecursiveType).nestedOne as RecuriveType).nestedTwo.key;
/*
red squiggly line goes away and understands that nestedTwo is of type SomeType
*/

I am not sure if this is the limitation of Typescript itself since documentation uses this kind of recursion and the code works without narrowing; but the error highlighting is a nuisance when the code is right. Maybe resolution ordering is the issue at hand, instead of going deep, it should rise up from the deepest possibility.

Screenshot

image

Metadata

Metadata

Assignees

Labels

*questionIssue represents a question, should be posted to StackOverflow (VS Code)typescriptTypescript support issues

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions