microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.27k stars 12.52k forks source link

type check dynamic imports from constant string literal #60593

Closed scarf005 closed 1 day ago

scarf005 commented 4 days ago

πŸ” Search Terms

dynamic import constant string infer type any

βœ… Viability Checklist

⭐ Suggestion

statically analyze type of dynamic import if path is statically analyzable, such that

export {}

const polars = "nodejs-polars" as const
//    ^? const polars: "nodejs-polars"

const pl = await import(polars)
//    ^? const pl: typeof import("file:///node_modules/nodejs-polars/bin/index")

as type of polars is "nodejs-polars", not string, typescript should treat import("nodejs-polars") the same as import(polars).

πŸ“ƒ Motivating Example

https://github.com/denoland/deno/issues/26965

export {}

const polars = "nodejs-polars" as const

const pl = await import("nodejs-polars")
//    ^? const pl: typeof import("file:///node_modules/nodejs-polars/bin/index")

const pl2 = await import(polars)
//    ^? const pl2: typeof import("file:///node_modules/nodejs-polars/bin/index")

Playground Link

πŸ’» Use Cases

  1. What do you want to use this for?

writing type safe javascript module, with version string abstracted away to manage versions easily

const preact = "preact@10.24.3"
const { h, render } = await import(`https://esm.sh/${preact}`)
const { computed, effect, signal } = await import(`https://esm.sh/@preact/signals@1.3.0?deps=${preact}`)

console.log(`preact version is ${preact}`)
  1. What shortcomings exist with current approaches?
  2. What workarounds are you using in the meantime?

due to type check not working in above example, version string has to be duplicated, which might cause bug when naively regex-replacing.

import { h, render }  from "https://esm.sh/preact@10.24.3"
import { computed, effect, signal } from "https://esm.sh/@preact/signals@1.3.0?deps=preact@10.24.3"

console.log("preact version is preact@10.24.3")
MartinJohns commented 4 days ago

Duplicate of #32401.

typescript-bot commented 1 day ago

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.