importing type declaration files · Issue #16472 · microsoft/TypeScript (original) (raw)

I updated to 2.3.4 -> 2.4.0 and now I'm unable to do import * as lib from '@types/lib', as it throws an error: error TS6137: Cannot import type declaration files.

I thought that this was a great way to programatically include type definitions into a clearly defined namespace, which then gets scrubbed at compile time (as opposed to /// referencing them).

I can understand blocking the direct importing of def files in ambiguous contexts to help prevent runtime errors (i.e. if you import * as lib from 'lib', then you should expect it to only import a non-def file), but I feel that doing an import of something in the @types package namespace, or a file ending with .d.ts should be allowed, as it's explicitly importing typings.

It helps to work around things where you actually want types but don't use a library.

For example, with AWS lambda:

import * as lambda from '@types/aws-lambda'

export const handler = (event : lambda.APIGatewayEvent, context : lambda.Context, callback : lambda.Callback) => { // stuff }

It's clear that you're not using an actual aws-lambda library, just the types.
It's also clear where the lambda namespace came from, so new developers to the code don't wonder where random namespaces might come from, which is what happens when you rely solely on the ambient type definition:

export const handler = (event : AWSLambda.APIGatewayEvent, context : AWSLambda.Context, callback : AWSLambda.Callback) => { // stuff }

It helps to work around problems like defining types to library A which is designed to fit the same API as library B.

i.e. the mysql2 package is designed to fit mostly the same API as the mysql package, so you can cover the majority of usage by just defining this typescript def file:

declare module 'mysql2' { export * from '@types/mysql' }

again, as you've not installed the mysql package, it's clear where the types are coming from, (rather than doing export * from 'mysql'.