ts笔记索引签名

索引签名用于约束知道key、value类型的数据的结构,索引签名必须是 string 或者 number或者symbols。格式{ [key: keyType]: valueType },string、symbols用于约束对象,number用于约束数组。

JavaScript 在一个对象类型的索引签名上会隐式调用 toString 方法,而在 TypeScript 中这么使用会直接抛出错误。

const obj = {
  toString() {
    return 'Hello';
  }
};

const foo = {}

foo[obj] = 'World'

console.log(foo[obj]); //  World
console.log(foo['Hello']); // World
const obj = {
  toString() {
    return 'Hello';
  }
};

const foo: any = {};

// 类型“{ toString(): string; }”不能作为索引类型使用
foo[obj] = 'World';

// 正常
foo[obj.toString()] = 'World';

使用索引签名创建一个指定结构的对象

// 对象foo的key必须是string,值是一个包含message属性的对象
const foo: { [index: string]: { message: string } } = {};


foo.a = {message: 'hello' } // ok 创建
foo.a.message; // ok 读取

foo.b = { messages: 'some message' }; // ERROR 

当你声明一个索引签名时,所有明确的成员都必须符合索引签名

interface Foo {
  [key: string]: number;
  x: number;
  y: string; // ERROR 必须是number
}


interface Foo {
  [key: number]: string;
  2: number
}

const foo: Foo = ['1', '2', '3']; // OK

索引签名可以通过映射类型来使索引字符串为联合类型中的一员

type Index = 'a' | 'b' | 'c';
type FromIndex = { [k in Index]?: number };

const good: FromIndex = { b: 1, c: 2 };

嵌套索引签名

interface NestedCSS {
  color?: string;
  nest?: {
    [selector: string]: NestedCSS;
  };
}

const example: NestedCSS = {
  color: 'red',
  nest: {
    '.subclass': {
      color: 'blue'
    }
  }
}
常用网站: SegmentFault | GitHub | 掘金社区
原文地址:https://www.cnblogs.com/yesyes/p/15539175.html