xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript 协变与逆变 All In One

TypeScript 协变与逆变 All In One

Covariance and contravariance

协变与逆变

协变与逆变(Covariance and contravariance)是在计算机科学中,描述具有父/子型别关系的多个型别通过型别构造器、构造出的多个复杂型别之间是否有父/子型别关系的用语。

https://zh.wikipedia.org/wiki/协变与逆变

https://zh.wikipedia.org/wiki/协变与逆变#泛型类型

TypeScript

generic / 泛型

// function generic ✅

function FG<T>(arg: T): T {
  return arg;
}

// function FGError(arg: T): T {
//   return arg;
// }

// arrow function generic ✅
const AFG = <T,>(args: T): T => args;
const AFG2 = <T extends unknown>(args: T): T => args;
const AFG3 = <T extends any>(args: T): T => args;
const AFG4 = <T extends {}>(args: T): T => args;
const AFG6 = <T extends Object>(args: T): T => args;

// const AFGError = <T>(args: T): T => args;
// const AFGError = (args: T): T => args;

// const AFG = <T>(value: T): T => value;
// JSX element 'T' has no corresponding closing tag.(17008)

// const AFG = <T extends object>(args: T): T => args;
// Argument of type 'string' is not assignable to parameter of type 'object'.(2345)

// ✅ arrow function & typescript generic
const AFG = <T,>(args: T): T => args;
// const AFG = <T extends {}>(args: T): T => args;
// const AFG = <T extends unknown>(args: T): T => args;
// const AFG = <T extends any>(args: T): T => args;
// const AFG = <T extends Object>(args: T): T => args;


AFG('abc');
AFG(123);
AFG({year: '2022'});

// interface generic ✅
interface IG<T> {
  [key: string]: T;
  (arg: T): T;
}

interface IGError<T> {
  [key: string]: T;
  // func: (arg: T) => T;
}

interface IGBug {
  // <T>[key: string]: T;
  <T>(arg: T): T;
}

// class generic ✅


https://www.typescriptlang.org/docs/handbook/generics.html
https://www.typescriptlang.org/docs/handbook/2/generics.html

infer

type ParamType<T> = T extends (param: infer P) => any ? P : T;

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#type-inference-in-conditional-types

https://www.typescriptlang.org/docs/handbook/type-inference.html

refs

TypeScript LeetCode 面试题 All In One

https://www.cnblogs.com/xgqfrms/p/13611172.html#5051605



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-05-02 12:42  xgqfrms  阅读(76)  评论(3编辑  收藏  举报