typescript - 如何在打字稿中不使用选项(?)删除属性
问题描述
我有关于删除属性的问题。例如:
type Person<GN> = {
getName: GN extends never ? never : GN,
}
const foo = <GN>(person: Person<GN>) => person
const first = foo({}) // should work
const second = foo({
getName: (name: string) => name,
})
在这种情况下,首先不需要 getName 属性。我该如何解决。
使用可选的“?” 属性会导致输出不清晰。例如
type Person<GN> = {
getName?: GN,
}
const foo = <GN>(person: Person<GN>) => person
const first = foo({}) // should work
first.getName // shouldn't exist 'getName' => but still have
const second = foo({
getName: (name: string) => name,
})
second.getName // should exist getName but in this case is optional property
我怎样才能清楚地输出?谢谢阅读。
解决方案
因此,您希望first
type 被推断为{}
,并且second
type 为{ getName: (name: string) => string; }
?
这是一种方法:
type Person<GN> = { getName: GN }
const foo = <GN, P extends Partial<Person<GN>>>(person: P) => person;
const first = foo({}) // const first: {}
const second = foo({ // const second: { getName: (name: string) => string; }
getName: (name: string) => name,
})
推荐阅读
- google-api - .NET 的 Google API 客户端:如何实现指数退避
- mysql - 如何连接三个表?计数和平均 SQL
- javascript - 移动设备上的全日历回调
- firebase - cordova-plugin-firebase verifyPhoneNumber 应用程序在尝试发送时崩溃
- prolog - 比较 Prolog 中的两个谓词
- reactjs - 如何为使用参数调用 React setState 的函数创建 TypeScript 类型?
- python - 使用 Python 最小化方程
- ios - IOS 11 拖放 - 导入/加载 .cbz 文件
- ios - 如何在不创建新框架的情况下将当前框架发布为 cocoapods?
- ads - 未使用 videojs 触发的 Google DAI 插播事件