typescript - 打字稿按属性类型省略或排除
问题描述
我想根据这些属性的类型创建一个仅具有父类型的某些属性的新类型。
例如,我想要一个只包含字符串的 Post 类型。
type Post = {
id: string;
title: string;
numberOfLikes: number;
...
}
// This doesn't work
type PostStringsOnly = Extract<Post, string>
const postOnlyWithStringKeys: PostStringsOnly = {
id: "123",
title: "The best post!"
}
我想将它用于我不知道前面所有键的通用类型。所以特别省略“numberOfLikes”是行不通的。它需要按类型。
解决方案
type Post = {
id: string;
title: string;
numberOfLikes: number
}
type PostStringsOnly = Omit<Post, 'numberOfLikes'>
const postOnlyWithStringKeys: PostStringsOnly = {
id: "123",
title: "The best post!"
}
推荐阅读
- facebook-messenger - One-time notification message_optins callback not being received by testers, is being received by administrator
- teradata - 字符串转换为数值失败:Teradata 插入
- c# - 从扩展 HttpClient 的类中使用 GetAsync 时如何模拟它?
- bash - 在 Bash 中迭代这个数组
- unit-testing - 有没有办法使用Vue从url动态加载图像?
- android - 对每个 DB 条目执行请求
- python - 虽然我的电脑上已经安装了表格,但每次运行下面的代码时都会出现错误
- ls - !ls -aF 与 !ls -af 之间的区别
- c# - 带有 .NET 5 rc1 blazor Web 程序集的 Serilog 无法正常工作
- java - macos maven 包卡在添加目录 META-INF/