Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

node.js - Right way to reference platform-specific types in isomorphic Typescript library

I'm trying to write a Typescript library that I'd like to be able to include when targeting both the browser and Node. I have two problems: referring to platform-specific types in the body of the code, and the inclusion of those types in the generated .d.ts declarations that accompany the transpiled JS.

In the first case, I want to write something like

  if (typeof window === "undefined") {
    // Do some Node-y fallback thing
  } else {
    // Do something with `window`
  }

This fails to compile if I don't include "dom" in my lib compiler option (that is, if I just say lib: ["es2016"] in tsconfig), because the global window is not defined. (Using window is just an example of something out of lib.dom.d.ts, it may also be fetch or a Response or Blob, etc.) The point is that the code should already be safe at runtime by checking for the existence of the global object before using it, it's the type side that I can't figure out.

In the second case, I'm getting an error trying to include the library after it builds. I can build the library using "dom" in the lib option, and the resulting output includes typings with e.g. declare export function foo(x: string | Blob): void. The problem is, if the consuming code doesn't include a definition for Blob (no "dom" lib), it fails to compile, even though it's only actually calling foo with a string (or not using foo at all!).

I don't want my library (or the consumer) to try to pollute the global namespace with fake window or Blob declarations if I can help it. More isometric libraries have been popping up but I haven't found a good Typescript example to follow. (If it's too complex a topic for SO, I'd still greatly appreciate a pointer to documentation or an article/blog post.)

question from:https://stackoverflow.com/questions/65848540/right-way-to-reference-platform-specific-types-in-isomorphic-typescript-library

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...