typescript - TypeScript 在隐式获取值时定义变量类型
问题描述
如果我在 javascript 中做这样的事情
const { peer, users, ...otherProps } = props;
我如何在 TypeScript 中做同样的事情才能定义这些变量将具有的类型?
解决方案
您可以键入props
:
interface TypeOfProps {
peer: string;
users: number;
randomProp: string;
}
const props: TypeOfProps = {
peer: "peer",
users: 5,
randomProp: "hah"
}
const { peer, users, ...otherProps } = props;
或传播对象:
const { peer, users, ...otherProps}: TypeOfProps = props;
两者都将正确推断 和的peer
类型。users
otherProps
推荐阅读
- mapping - NCL 绘制没有环绕框的地图
- python - 使用python elementree xml解析器和循环的宁静分页
- javascript - 每次生产 Kafka 消息时都需要连接吗?
- blazor-server-side - 如何从“无法重新连接到服务器。重新加载页面以恢复功能”中使用 Blazor Web 应用程序以编程方式恢复或重新启动。
- asp.net - Net core 3.1 Google authentication GetExternalLoginInfoAsync 由于某些浏览器中的空cookie而返回null
- c++ - 这个函数中 std::bad_alloc 的原因是什么?
- r - 当闪亮的应用程序通过单击按钮运行时如何运行 R 脚本?
- android - 如何从 Firebase 实时数据库中读取数据?
- django - modelformset 重复我的字段并从我的数据库中获取值
- android-studio - Kotlin 文档:链接到具有不同签名的方法?