TypeScript基于类型创建新类型

类型拓展

一、泛型 Generics - Types which take parameters

泛型能够创建一个可以在多种类型而不是单一类型上工作的组件

1 函数泛型

// 泛型

interface IPerson {
  realName: string;
  age: number;
  gender: boolean;
}

const person: IPerson = {
  realName: '小明',
  age: 18,
  gender: true,
};

// 1、未使用泛型
function getProperty(person: IPerson, key: keyof IPerson) {
  return person[key];
}

/**
 * 未使用泛型的时候,getProperty返回值类型有3中情况【 string | number | boolean】
 * 在具体使用某个返回值的时候需要进行类型判断或者强制类型断言
 */
function printMsg() {
  const realName = getProperty(person, 'realName') as string;
  const gender = getProperty(person, 'gender') as boolean;
  let age = getProperty(person, 'age');

  if (typeof age === 'number') {
    age = age + 10;
  }
  console.log(`姓名: ${realName};年龄: ${age};性别: ${gender === true ? '男' : '女'}`);
}

printMsg();

// 2、使用泛型
function getProperty<T, K extends keyof T>(person: T, key: K) {
  return person[key];
}

function printMsg() {
  const realName = getProperty(person, 'realName');
  const gender = getProperty(person, 'gender');
  let age = getProperty(person, 'age');
  age = age + 10;

  console.log(`姓名: ${realName};年龄: ${age};性别: ${gender === true ? '男' : '女'}`);
}

2 interfact泛型

3 type 泛型

4 class 泛型

二、类型运算符 Keyof Type Operator - Using the keyof operator to create new types

三 、类型运算符 Typeof Type Operator - Using the typeof operator to create new types

四、索引访问类型 Indexed Access Types - Using Type['a'] syntax to access a subset of a type

五、条件类型 Conditional Types - Types which act like if statements in the type system

六、映射类型 Mapped Types - Creating types by mapping each property in an existing type

七、模板文字类型Template Literal Types - Mapped types which change properties via template literal strings

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容