簡體   English   中英

嘗試將屬性從一個 object 分配給另一個時出現 TypeScript 錯誤

[英]TypeScript errors while trying to assign properties from one object to another

我的代碼:

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]))

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; }'

看起來kstring類型。 我有一些嘗試:

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'.

怎么了?

因為您正在嘗試像這樣評估 object :

{
  activeRequests: number | boolean | undefined, 
  test: number | boolean | undefined
}

至:

{
  activeRequests: number, 
  test: boolean,
}

因為 partial 和 stateKeys 部分。

解決方案很簡單:

const set = (state: state, p: pState) => ({...state, ...p})

如果沒有 generics,您將無法做到這一點。 另外,您正在嘗試將部分未定義的值分配給不允許未定義的類型。 所以你需要處理這種情況。 這是一個潛在的解決方案:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM