学无先后,达者为师

网站首页 编程语言 正文

ts之定义对象高级使用 Record

作者:不求人0 更新时间: 2023-02-28 编程语言

目录

  • ts之定义对象高级使用 Record
    • 简单使用
    • 复杂对象

ts之定义对象高级使用 Record

Record<key type, value type> 第一个key值类型,第二个为obj[key]数据的类型
Record<string, unknown> 任意对象

简单使用

let termMap1 = {} as Record<string, string>;
//  定义对象 Record<string, string> 第一个string为key值,第二个为obj[key]数据的类型
termMap = {
     age:10, // 不能将类型“number”分配给类型“string”。
     num:'11'
 }
console.log('termMap1',termMap1 );

复杂对象

// Record 来限制 对象的key和value
type P = {
  [key: string]: number;
};
let p: P = { ppp: 10, ooo: 10 };
// k不是泛型  K泛型

// 01 Record 来限制 对象的key和value
type PP = Record<string, number>;
let pp: PP = {
  ppp: 10,
  ooo: 10,
};

type PP2 = Record<string, string>;
let pp2: PP2 = {
  ppp: "10", //  ppp: '10' 不能将类型“number”分配给类型“string”
  ooo: "10",
};

// 02 Record 来限制 复杂对象的key和value
interface term {
  info: number;
  checked: boolean;
}
type TermMap = Record<string, term>;
// item项目  key:string  value: { info: 10, checked: true }
let termMap: TermMap = {
  xxx: {
    info: 10,
    checked: true,
  },
};

// 03 Record 来限制 复杂对象的key和value
interface info_config {
  name: string;
}
interface term2 {
  info: info_config;
  checked: boolean;
}
let termMap2 = {} as Record<string, term2>;
// 定义对象 Record<string, string> 第一个string为key值,第二个为obj[key]数据的类型
termMap2 = {
  xxx: {
    info: {
      name: "111",
    },
    checked: true,
  },
};

// 04 Record 来限制 复杂对象的key和value
interface info_config3 {
  name: string[];
}
interface term3 {
  info: info_config3;
  checked: boolean;
}
let termMap3 = {} as Record<string, term3>;
// 定义对象 Record<string, string> 第一个string为key值,第二个为obj[key]数据的类型
termMap3 = {
  xxx: {
    info: {
      name: ["1", "2"],
    },
    checked: true,
  },
};

原文链接:https://blog.csdn.net/weixin_47409897/article/details/127772122

栏目分类
最近更新