ts 使用 keyof typeof

传递参数

const cats = {
  "Coding Cat": "https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif",
  "Compiling Cat": "https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif",
  "Testing Cat": "https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif"
};

function f(a: keyof typeof cats) {
  console.log(a);
}

// f("x"); // error
f("Coding Cat"); // ok

参数断言

const translates = {...};

function checkOrigin(origin: string): origin is keyof typeof translates {
  if (translates.hasOwnProperty(origin)) return true;
  else throw "error origin: " + origin;
}

if (checkOrigin(argv.origin)) {
  translates[argv.origin]...
}
posted @ 2020-01-31 13:58  Ajanuw  阅读(3571)  评论(0编辑  收藏  举报