惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
TypeScript: Augmenting global and lib.dom.d.ts
2020-07-17 · via oida.dev | TypeScript, Rust

Recently I wanted to use a ResizeObserver in my application. ResizeObserver recently landed in all major browsers, but when you use it in TypeScript — at the time of this writing — ResizeObserver won’t be recognized as a valid object (or constructor). So why is that?

How DOM API types land in TypeScript #

TypeScript stores types to all DOM APIs in lib.dom.d.ts. This file is auto-generated from Web IDL files. Web IDL stands for Web Interface Definition Language and is a format the W3C and WHATWG use to define interfaces to web APIs. It came out around 2012 and is a standard since 2016.

When you read standards at W3C — like on Resize Observer — you can see a parts of a definition or the full definition somewhere within the specification. Like this one:

enum ResizeObserverBoxOptions {
"border-box", "content-box", "device-pixel-content-box"
};

dictionary ResizeObserverOptions {
ResizeObserverBoxOptions box = "content-box";
};

[Exposed=(Window)]
interface ResizeObserver {
constructor(ResizeObserverCallback callback);
void observe(Element target, optional ResizeObserverOptions options);
void unobserve(Element target);
void disconnect();
};

callback ResizeObserverCallback = void (sequence<ResizeObserverEntry> entries, ResizeObserver observer);

[Exposed=Window]
interface ResizeObserverEntry {
readonly attribute Element target;
readonly attribute DOMRectReadOnly contentRect;
readonly attribute FrozenArray<ResizeObserverSize> borderBoxSize;
readonly attribute FrozenArray<ResizeObserverSize> contentBoxSize;
readonly attribute FrozenArray<ResizeObserverSize> devicePixelContentBoxSize;
};

interface ResizeObserverSize {
readonly attribute unrestricted double inlineSize;
readonly attribute unrestricted double blockSize;
};

interface ResizeObservation {
constructor(Element target);
readonly attribute Element target;
readonly attribute ResizeObserverBoxOptions observedBox;
readonly attribute FrozenArray<ResizeObserverSize> lastReportedSizes;
};

Browsers use this as a guideline to implement respective APIs. TypeScript uses these IDL files to generate lib.dom.d.ts. The TS JS Lib generator project scrapes web standards and extracts IDL information. Then an IDL to TypeScript parser generates the correct typings.

Pages to scrape are maintained manually. The moment a specification is far enough and supported by all major browsers, people add a new resource and see their change released with an upcoming TypeScript version. So it’s just a matter of time until we get ResizeObserver in lib.dom.d.ts.

If we can’t wait, we just can add the typings ourselves. And only for the project we currently work with.

Ambient declarations #

Let’s assume we generated the types for ResizeObserver. We would store the output in a file called resize-observer.d.ts. Here are the contents:

type ResizeObserverBoxOptions =
"border-box" |
"content-box" |
"device-pixel-content-box";

interface ResizeObserverOptions {
box?: ResizeObserverBoxOptions;
}

interface ResizeObservation {
readonly lastReportedSizes: ReadonlyArray<ResizeObserverSize>;
readonly observedBox: ResizeObserverBoxOptions;
readonly target: Element;
}

declare var ResizeObservation: {
prototype: ResizeObservation;
new(target: Element): ResizeObservation;
};

interface ResizeObserver {
disconnect(): void;
observe(target: Element, options?: ResizeObserverOptions): void;
unobserve(target: Element): void;
}

export declare var ResizeObserver: {
prototype: ResizeObserver;
new(callback: ResizeObserverCallback): ResizeObserver;
};

interface ResizeObserverEntry {
readonly borderBoxSize: ReadonlyArray<ResizeObserverSize>;
readonly contentBoxSize: ReadonlyArray<ResizeObserverSize>;
readonly contentRect: DOMRectReadOnly;
readonly devicePixelContentBoxSize: ReadonlyArray<ResizeObserverSize>;
readonly target: Element;
}

declare var ResizeObserverEntry: {
prototype: ResizeObserverEntry;
new(): ResizeObserverEntry;
};

interface ResizeObserverSize {
readonly blockSize: number;
readonly inlineSize: number;
}

declare var ResizeObserverSize: {
prototype: ResizeObserverSize;
new(): ResizeObserverSize;
};

interface ResizeObserverCallback {
(entries: ResizeObserverEntry[], observer: ResizeObserver): void;
}

We declare a ton of interfaces, and some variables that implement our interfaces, like declare var ResizeObserver which is the object that defines the prototype and constructor function:

declare var ResizeObserver: {
prototype: ResizeObserver;
new(callback: ResizeObserverCallback): ResizeObserver;
};

This already helps a lot. We can use the — arguably — long type declarations and put them directly in the file where we need them. ResizeObserver is found! We want to have it available everywhere, though.

Augmenting global #

Thanks to TypeScript’s declaration merging feature, we can extend namespaces and interfaces as we need it. There are several articles here on how to extend Object, JSX types, and more. This time, we’re extending the global namespace.

The global namespace contains all objects and interfaces that are, well, globally available. Like the window object (and Window interface), as well as everything else where which should be part of our JavaScript execution context. We augment the global namespace and add the ResizeObserver object to it:

declare global { // opening up the namespace
var ResizeObserver: { // mergin ResizeObserver to it
prototype: ResizeObserver;
new(callback: ResizeObserverCallback): ResizeObserver;
}
}

Let’s put resize-observer.d.ts in a folder called @types. Don’t forget to add the folder to both the sources that TypeScript shall parse, as well as the list of type declaration folders in tsconfig.json

{
"compilerOptions": {
//...
"typeRoots": ["@types", "./node_modules/@types"],
//...
},
"include": ["src", "@types"]
}

Since there might be a significant possibility that ResizeObserver is not yet available in your target browser, make sure that you make the ResizeObserver object possibly undefined. This urges you to check if the object is available:

declare global {
var ResizeObserver: {
prototype: ResizeObserver;
new(callback: ResizeObserverCallback): ResizeObserver;
} | undefined
}

In your application:

if(typeof ResizeObserver !== 'undefined') {
const x = new ResizeObserver((entries) => {})
}

This makes working with ResizeObserver as safe as possible!

Troubleshooting #

It might be that TypeScript doesn’t pick up your ambient declaration files and the global augmentation. If this happens, make sure that:

  1. You parse the @types folder via the include property in tsconfig.json
  2. Your ambient type declaration files are recognized as such by adding them to types or typeRoots in the tsconfig.json compiler Options
  3. Add export {} at the end of your ambient declaration file so TypeScript recognizes this file as a module

Further reading #

All the links above, plus:

Related Articles