Skip to content

Compiling with -d should emit triple-slash lib paths #28195

Closed
@bcherny

Description

@bcherny

Search Terms

Triple slash, reference, path, lib, library, types, typings, dom

Suggestion

When compiling a .ts file with declaration: true, TSC should emit triple-slash reference paths for all libs consumed by the .ts file.

Problem

Say I publish typings for my package foo to NPM, and foo depends on DOM typings. I then include foo in my project (npm install foo). There are a few things that can happen:

  1. If foo's typings include <reference lib="dom" />:
  • foo has access to DOM
  • My project has access to DOM types (is this sort of leakage desirable?)
  1. If my project includes dom (or uses the same triple-slash directive as in 1):
  • foo has access to DOM
  • My project has access to DOM types
  1. Neither my project nor foo include <reference lib="dom" />:
  • foo errors wherever it uses DOM types (but I have to inspect node_modules/foo/index.d.ts to see those errors)

  • My project treats foo's DOM types as anys (should this error in strict mode?)

    // foo.d.ts
    export function a(): HTMLInputElement
    
    // myProject/index.ts
    import {a} from 'foo'
    a() // any

Solution

If tsc -d generated triple-slash directives for foo/index.d.ts, we can ensure that we're always in case (1). This is nice because if my project doesn't use dom, I shouldn't have to declare it for the sake of foo like I did in (2); it also avoids the any from (3).

// Before
export function a(): HTMLInputElement

// After
/// <reference lib="dom" />
export function a(): HTMLInputElement

An open question is how strict should TSC be? Ie. If foo uses dom but fails to reference it, should this cause a compile error in my project (and a nice message suggesting I add a reference to dom)?

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableA PR has been opened for this issueIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions