[英]How to clone only type properties in typescript
假设我有代码:
type SimpleState =
{
a1: string
// little more properties
}
type ComplexState =
SimpleState
& {
b1: numeric,
c1: boolean
// many other properties
}
const workingState :ComplexState = // all properties initialozation
const stateParam :SimpleState = workingState;
cacheSimpleState(stateParam)
在运行时 cacheSimpleState 接收具有所有属性的 ComplexState 对象。 有没有办法将 workingState 克隆到 stateParam 以便它只有 SimpleState 属性?
不幸的是,不是。 Typescript 无法在运行时检查接口成员。
一个选项,虽然不是很花哨,是手动列出道具:
function cacheSimpleState<T extends SimpleState>(data: T): SimpleState {
return {
a1: data.a1
}
}
这样,如果SimpleState
需要更多数据,至少您的构建会知道。 但是,如果出现可选参数,您需要小心。 一个选项是:
type SimpleState =
{
a1: string;
b1?: string;
}
const defaultSimpleState: SimpleState = { // All the mandatory props
a1: ''
}
const defaultOptionalState: SimpleState = { // All the optional props
...defaultSimpleState,
b1: ''
}
function cacheSimpleState<T extends SimpleState>(data: T): SimpleState {
let props: Partial<SimpleState> = {};
for (let prop in data) {
if (prop in defaultSimpleState || prop in defaultOptionalState) {
props = {...props, [prop]: data[prop]};
}
}
return props as SimpleState;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.