[英]TypeScript errors while trying to assign properties from one object to another
My code:我的代码:
const state = { activeRequests: 0, test: true };
type state = typeof state;
type pState = Partial<state>;
type stateKeys = keyof state; // "activeRequests" | "test"
...
set: (state: state, p: pState) => Object.keys(p).forEach(k => (state[k] = p[k]))
Error at state[k] = p[k]
: state[k] = p[k]
处的错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ activeRequests: number; test: boolean; }'.
No index signature with a parameter of type 'string' was found on type '{ activeRequests: number; test: boolean; }'
Looks like k
has string
type.看起来
k
有string
类型。 There are some of my attempts:我有一些尝试:
Object.keys(p).forEach((k: stateKeys) => state[k].push(p[k]))
Error: Type 'string' is not assignable to type '"activeRequests" | "test"'`.
Object.keys(p).forEach(k => (state[k as stateKeys] = p[k])
Error: Type 'any' is not assignable to type 'never'`
(Object.keys(p) as stateKeys[]).forEach(k => (state[k] = p[k]))
Error: Type 'number | boolean | undefined' is not assignable to type 'never'.
Type 'undefined' is not assignable to type 'never'.
What is wrong?怎么了?
because you are trying to assing object like this:因为您正在尝试像这样评估 object :
{
activeRequests: number | boolean | undefined,
test: number | boolean | undefined
}
to:至:
{
activeRequests: number,
test: boolean,
}
because of the partial and stateKeys part.因为 partial 和 stateKeys 部分。
Solution is simple like that:解决方案很简单:
const set = (state: state, p: pState) => ({...state, ...p})
You can't do that cleanly without generics.如果没有 generics,您将无法做到这一点。 Plus you are trying to assign a partially undefined value to a type that doesn't allow undefined.
另外,您正在尝试将部分未定义的值分配给不允许未定义的类型。 So you need to handle that scenario.
所以你需要处理这种情况。 Here's a potential solution:
这是一个潜在的解决方案:
var t = function<TState>(state: TState, p: Partial<TState>) {
let keys = Object.keys(p) as (keyof TState)[];
for (let key of keys) {
state[key] = p[key] ?? state[key];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.