TypeScript 中的字典(Dictionary)通常指代的是对象(Object),可以用于存储键值对。在字典中,要判断某个键是否存在,可以通过判断该键是否在对象中进行。以下是两种方法:
       in
      
      操作符:
     const myDict = { a: 1, b: 2 };
if ('a' in myDict) {
  console.log('a exists in the dictionary.');
使用 hasOwnProperty 方法: 
const myDict = { a: 1, b: 2 };
if (myDict.hasOwnProperty('a')) {
  console.log('a exists in the dictionary.');
这两种方法都可以判断对象是否有某个键。in 操作符可以检查键是否存在于对象本身或其原型链中,而 hasOwnProperty 方法只检查键是否存在于对象本身中。
另外,如果您需要对 TypeScript 中的字典进行类型定义,可以使用索引签名来定义:
interface MyDict {
  [key: string]: number;
const myDict: MyDict = { a: 1, b: 2 };
这里的 [key: string]: number 表示该字典的键为字符串类型,值为数字类型。


