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?
您可以使用 强制数组具有元组类型as const。这也使 type readonly,但如果只是你使用它来解构返回值,那没问题。
const getPersonValues = () => {
return [person.name, person.age, person.isHere] as const;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27 次 |
| 最近记录: |