Skip to content

Cannot use class as type if nested into object or class Β #46938

@Danielku15

Description

@Danielku15

Bug Report

πŸ”Ž Search Terms

nested class type object

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type System Behavior

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class Test {}
const Const = {
    Test: Test,
    Test2: class {

    }
}
class Class {
    static Test = Test;
    static Test2 = class {
    }
}
declare const ConstAsInTsDef: { // d.ts files will look like this for the const Const = {} variant above
    Test: typeof Test
}

const a: Const.Test = new Const.Test();
const b: Const.Test2 = new Const.Test2();
const c: Class.Test = new Class.Test();
const d: Class.Test2 = new Class.Test2();
const e: ConstAsInTsDef.Test = new ConstAsInTsDef.Test(); 

πŸ™ Actual behavior

TypeScript does not allow to use the nested types within objects or classes as part of type annotations. It complains with errors like Cannot find namespace 'Const'.ts(2503) as TypeScript only seem to allow referencing nested types only if they are nested using namespaces

πŸ™‚ Expected behavior

We should be able to use also classes/types aliased through objects or nested classes as type annotations in variables, return types etc.

Use Case

This topic relates a bit to #4529

I am bundling up my library into an all-in-one module (using Rollup) containing one entry point to my library while I want to keep a bit of a module-alike organization of my classes through this nesting approach. Considering all the current restrictions regarding exports and namespaces going for nesting is currently the "best" approach with keeping 1 file for your library.

Consumers of my library can access all the classes to create instances but they cannot use my types in their codebases to annotate their variables and functions.

My library is available in a wide variety of environments supporting module (ESM, UMD) and non-module (classical browser script include) usages.

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