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

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Covariance and Contravariance in TypeScript
Dmitri Pavlutin · 2021-10-14 · via Dmitri Pavlutin Blog

Learning covariance and contravariance in TypeScript could be tricky (I know from my experience!), but knowing them is a great addition to understanding types and subtyping.

In this post, you'll read an accessible explanation of covariance and contravariance concepts.

Table of Contents

  • 1. Subtyping
  • 2. Covariance
  • 3. Contravariance
  • 4. Functions subtyping
  • 5. Conclusion

1. Subtyping

Subtyping is a form of polymorphism in which a subtype is associated with a base type by some form of substitutability.

The substitutability means that a variable of base type can also accept subtype values.

For example, let's define a base class User and a class Admin that extends User class:


class User {

username: string;

constructor(username: string) {

this.username = username;

}

}

class Admin extends User {

isSuperAdmin: boolean;

constructor(username: string, isSuperAdmin: boolean) {

super(username);

this.isSuperAdmin = isSuperAdmin;

}

}


Since Admin extends User (Admin extends User), you could say that Admin is a subtype of the base type User.

User and Admin Classes

The substitutability of Admin (subtype) and User (base type) consists, for example, in the ability to assign to a variable of type User an instance of type Admin:


const user1: User = new User('user1'); // OK

const user2: User = new Admin('admin1', true); // also OK


How can you benefit from the substitutability?

One of the great benefits is that you can define behavior that doesn't depend on details. In simple words, you can create functions that accept the base type as a parameter, but then you can invoke that function with subtypes.

For example, let's write a function that logs the user name to the console:


function logUsername(user: User): void {

console.log(user.username);

}


This function accepts arguments of type User, Admin, and instances of any other subtypes of User you might create later. That makes logUsername() more reusable and less bothered with details:


logUsername(new User('user1')); // logs "user1"

logUsername(new Admin('admin1', true)); // logs "admin1"


1.1 A few helpers

Now let's introduce the symbol A <: B — meaning "A is a subtype of B".

Because Admin is a subtype of User, now you could write shorter:

Let's also define a helper type IsSubtypeOf<S, P>, which evaluates to true if S if a subtype of P, and false otherwise:


type IsSubtypeOf<S, P> = S extends P ? true : false;


IsSubtypeOf<Admin, User> evaluates to true because Admin is a subtype of User:


type T11 = IsSubtypeOf<Admin, User>; // true


Subtyping is possible for many other types, including primitives and built-in JavaScript types.

For example, the literal string type 'Hello' is a subtype of string, the literal number type 42 is a subtype of number, Map<K, V> is a subtype of Object.


type T12 = IsSubtypeOf<'hello', string>; // true

type T13 = IsSubtypeOf<42, number>; // true

type T14 = IsSubtypeOf<Map<string, string>, Object>; // true


2. Covariance

Let's think about some asynchronous code that fetches User and Admin instances. Working with async code requires dealing with promises of User and Admin: Promise<User> and <: Promise<Admin>.

Here's an interesting question: having Admin <: User, does it mean that Promise<Admin> <: Promise<User> holds as well?

Let's make the experiment:


type T21 = IsSubtypeOf<Promise<Admin>, Promise<User>> // true


Having Admin <: User, then Promise<Admin> <: Promise<User> indeed holds true. This demonstrates that Promise type is covariant.

Covariance

Here's a definition of covariance:

A type T is covariant if having S <: P, then T<S> <: T<P>.

The covariance of a type is intuitive. If Admin is a subtype of User, then you can expect Promise<Admin> to be a subtype of Promise<User>.

Covariance holds for many types in TypeScript.

A) Promise<V> (demonstrated above)

B) Record<K,V>:


type RecordOfAdmin = Record<string, Admin>;

type RecordOfUser = Record<string, User>;

type T22 = IsSubtypeOf<RecordOfAdmin, RecordOfUser>; // true


C) Map<K,V>:


type MapOfAdmin = Map<string, Admin>;

type MapOfUser = Map<string, User>;

type T23 = IsSubtypeOf<MapOfAdmin, MapOfUser>; // true


3. Contravariance

Now let's consider the following generic type:


type Func<Param> = (param: Param) => void;


Func<Param> creates function types with one parameter of type Param.

Having Admin <: User, which of the expressions is true:

  • Func<Admin> <: Func<User>, or
  • Func<User> <: Func<Admin>?

Let's take a try:


type T31 = IsSubtypeOf<Func<Admin>, Func<User>> // false

type T32 = IsSubtypeOf<Func<User>, Func<Admin>> // true


Func<User> <: Func<Admin> holds true — meaning that Func<User> is a subtype of Func<Admin> . Note that the subtyping direction has flipped compared to the original types Admin <: User.

Such behavior of Func type makes it contravariant. Speaking generally, function types are contravariant in regards to their parameter types.

Contravariance

A type T is contravariant if having S <: P, then T<P> <: T<S>.

The subtyping direction of function types is in the opposite direction of the subtyping of the parameter types.


type FuncUser = (p: User) => void;

type FuncAdmin = (p: Admin) => void;

type T31 = IsSubtypeOf<Admin, User>; // true

type T32 = IsSubtypeOf<FuncUser, FuncAdmin>; // true


4. Functions subtyping

What is interesting about functions subtyping is that it combines both covariance and contravariance.

A function type is a subtype of a base type if its parameter types are contravariant with the base type' parameter types, and the return type is covariant* with the base type' return type.

*when strictFunctionTypes mode is enabled.

In other words, the subtyping for functions requires that the parameter types be contravariant, while the return types covariant.

Function Types Subtyping in TypeScript

For example:


type SubtypeFunc = (p: User) => '1' | '2';

type BaseFunc = (p: Admin) => string;

type T41 = IsSubtypeOf<SubtypeFunc, BaseFunc> // true


SubtypeFunc <: BaseFunc because:

A) parameter types are contravariant (subtyping direction flipped User :> Admin)
B) return types are covariant (same subtyping direction '1' | '2' <: string).

Knowing subtyping greatly helps to understand the substitutability of function types.

For example, having a list of Admin instances:


const admins: Admin[] = [

new Admin('john.smith', false),

new Admin('jane.doe', true),

new Admin('joker', false)

];


What types of callbacks does the admins.filter(...) accept?

Obviously, it accepts a callback with one parameter of type Admin:


const admins: Admin[] = [

new Admin('john.smith', false),

new Admin('jane.doe', true),

new Admin('joker', false)

];

const superAdmins = admins.filter((admin: Admin): boolean => {

return admin.isSuperAdmin;

});

console.log(superAdmins); // [ Admin('jane.doe', true) ]


But would admins.filter(...) accept a callback which parameter type is User?


const jokers = admins.filter((user: User): boolean => {

return user.username.startsWith('joker');

});

console.log(jokers); // [ Admin('joker', false) ]


Yes, admins.filter() accepts (admin: Admin) => boolean base type, but also its subtypes like (user: User) => boolean.

If a higher-order function accepts callbacks of a specific type, e.g. (admin: Admin) => boolean, then you can also supply callbacks that are subtypes of the specific type, e.g. (user: User) => boolean.

5. Conclusion

The type T is covariant if having 2 types S <: P, then T<S> <: T<P> (the subtyping direction is maintained). An example of a covariant type is the Promise<T>.

But if T<P> <: T<S> (the subtyping is flipped), then T is contravariant.

The function type is contravariant by the parameter types, but covariant by the return types.

Challenge: What other covariant or contravariant types do you know?