1. 程式人生 > 其它 >ts筆記-索引簽名

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 | 掘金社群