Jak*_*son 5 typescript typescript-generics typescript-utility
我有一个带有以下参数的函数:
const handleAccount = (
account: Partial<IAccountDocument>,
...
) => { ... }
Run Code Online (Sandbox Code Playgroud)
我无论如何都无法更改界面以IAccountDocument不需要某些字段,即我必须使用Partial<>. 我怎样才能使其IAccountDocument包含特定字段,同时也允许部分创建?
使用Pick实用程序类型选择一些强制属性并将其与Partial<IAccountDocument>.
// Let's say that a and b must be mandatory properties
interface IAccountDocument {
a: number
b: number
c: number
d: number
e: number
}
const handleAccount = (
account: Pick<IAccountDocument, "a" | "b"> & Partial<IAccountDocument>
) => {}
// valid
handleAccount({a: 123, b: 123, c: 123})
// not valid
handleAccount({c: 23})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3930 次 |
| 最近记录: |