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

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

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 TypeScript: Augmenting global and lib.dom.d.ts 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 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: The constructor interface pattern
2019-08-15 · via oida.dev | TypeScript, Rust

If you are doing traditional OOP with TypeScript, the structural features of TypeScript might sometimes get in your way. Look at the following class hierachy for instance:

abstract class FilterItem {
constructor(private property: string) {}
someFunction() { /* ... */ }
abstract filter(): void;
}

class AFilter extends FilterItem {
filter() { /* ... */ }
}

class BFilter extends FilterItem {
filter() { /* ... */ }
}

The FilterItem abstract class needs to be implemented by other classes. In this example by AFilter and BFilter. So far, so good. Classical typing works like you are used to from Java or C#:

const some: FilterItem = new AFilter('afilter'); // ✅

When we need the structural information, though, we leave the realms of traditional OOP. Let’s say we want to instantiate new filters based on some token we get from an AJAX call. To make it easier for us to select the filter, we store all possible filters in a map:

declare const filterMap: Map<string, typeof FilterItem>;

filterMap.set('number', AFilter)
filterMap.set('stuff', BFilter)

The map’s generics are set to a string (for the token from the backend), and everything that complements the type signature of FilterItem. We use the typeof keyword here to be able to add classes to the map, not objects. We want to instantiate them afterwards, after all.

So far everything works like you would expect. The problem occurs when you want to fetch a class from the map and create a new object with it.

let obj: FilterItem;
const ctor = filterMap.get('number');

if(typeof ctor !== 'undefined') {
obj = new ctor(); // 💣 cannot create an object of an abstract class
}

What a problem! TypeScript only knows at this point that we get a FilterItem back, and we can’t instantiate FilterItem. Since abstract classes mix type information and actualy language (something that I try to avoid), a possible solution is to move to interfaces to define the actual type signature, and be able to create proper instances afterwards:

interface IFilter {
new (property: string): IFilter;
someFunction(): void;
filter(): void;
}

declare const filterMap: Map<string, IFilter>;

Note the new keyword. This is a way for TypeScript to define the type signature of a constructor function.

Lots of 💣s start appearing now. No matter where you put the implements IFilter command, no implementation seems to satisfy our contract:

abstract class FilterItem implements IFilter { /* ... */ }
// 💣 Class 'FilterItem' incorrectly implements interface 'IFilter'.
// Type 'FilterItem' provides no match for the signature
// 'new (property: string): IFilter'.

filterMap.set('number', AFilter)
// 💣Argument of type 'typeof AFilter' is not assignable
// to parameter of type 'IFilter'. Type 'typeof AFilter' is missing
// the following properties from type 'IFilter': someFunction, filter

What’s happening here? Seems like neither the implementation, nor the class itself seem to be able to get all the properties and functions we’ve defined in our interface declaration. Why?

JavaScript classes are special: They have not only one type we could easily define, but two types! The type of the static side, and the type of the instance side. It might get clearer if we transpile our class to what it was before ES6: a constructor function and a prototype:

function AFilter(property) { // this is part of the static side
this.property = property; // this is part of the instance side
}

// instance
AFilter.prototype.filter = function() {/* ... */}

// not part of our example, but instance
Afilter.something = function () { /* ... */ }

One type to create the object. One type for the object itself. So let’s split it up and create two type declarations for it:

interface FilterConstructor {
new (property: string): IFilter;
}

interface IFilter {
someFunction(): void;
filter(): void;
}

The first type FilterConstructor is the constructor interface. Here are all static properties, and the constructor function itself. The constructor function returns an instance: IFilter. IFilter contains type information of the instance side. All the functions we declare.

By splitting this up, our subsequent typings also become a lot clearer:

declare const filterMap: Map<string, FilterConstructor>; /* 1 */

filterMap.set('number', AFilter)
filterMap.set('stuff', BFilter)

let obj: IFilter; /* 2 */
const ctor = filterMap.get('number')
if(typeof ctor !== 'undefined') {
obj = new ctor('a');
}

  1. We add FilterConstructors to our map. This means we only can add classes that procude the desired objects.
  2. What we want in the end is an instance of IFilter. This is what the constructor function returns when being called with new.

Our code compiles again and we get all the auto completion and tooling we desire. Even better: We are not able to add abstract classes to the map. Because they don’t procude a valid instance:

// 💣 Cannot assign an abstract constructor 
// type to a non-abstract constructor type.
filterMap.set('notworking', FilterItem)

Traditional OOP, weaved in into our lovely type system. ✅

Here’s a playground with the full code

Related Articles