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

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

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