在Typescript中获取元组的确定类型而不是组合类型

Jac*_*bdo 0 typescript typescript-typings

我有以下示例代码:

const person = {
  name: "abc",
  age: 123,
  isHere: true
};

const getPersonValues = () => {
  return [person.name, person.age, person.isHere];
};

const [name] = getPersonValues(); // type for "name" is string | number | boolean
Run Code Online (Sandbox Code Playgroud)

name 的类型在string | number | boolean这里显示,但我希望它是一个字符串。有没有办法做到这一点,而不必显式声明里面的确定类型getPersonValues

kay*_*ya3 5

您可以使用 强制数组具有元组类型as const。这也使 type readonly,但如果只是你使用它来解构返回值,那没问题。

const getPersonValues = () => {
  return [person.name, person.age, person.isHere] as const;
};
Run Code Online (Sandbox Code Playgroud)

游乐场链接