You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:Type 'string'无法赋值给类型'never'求解决方案

TypeScript 类型错误排查:Type 'string' is not assignable to type 'never'

这个错误的核心原因是:TypeScript 在循环遍历联合类型的 key 时,无法自动关联 inbound[key] 和 target[key] 的具体类型。遍历过程中,to 的类型被推断为 string | number | undefined,而 target[key] 的类型被错误缩小为 string & number(即 never 类型),导致赋值不兼容。

以下是几种可行的解决方式:

方案1:类型断言(简单直接)

因为已经通过 to !== undefined 过滤了 undefined 情况,直接把 to 断言为目标属性的类型即可:

function RETURN () {
    return {
        a : "name",
        b : 1,
        id : "any"
    }
}
type UpdateInput = {
    a ?: string,
    b ?: number
}
function UPDATE (target : ReturnType<typeof RETURN>, inbound : UpdateInput) {
    const keys = [
        "a",
        "b"
    ] as const
    for (const key of keys) {
        const to = inbound[key];
        if (to !== undefined) {
            target[key] = to as typeof target[key];
        }
    }
}

方案2:泛型函数细化类型

把赋值逻辑抽成泛型函数,让 TypeScript 能精确推断每个 key 对应的类型:

function RETURN () {
    return {
        a : "name",
        b : 1,
        id : "any"
    }
}
type UpdateInput = {
    a ?: string,
    b ?: number
}

function updateKey<K extends keyof UpdateInput>(target: ReturnType<typeof RETURN>, inbound: UpdateInput, key: K) {
    const to = inbound[key];
    if (to !== undefined) {
        target[key] = to;
    }
}

function UPDATE (target : ReturnType<typeof RETURN>, inbound : UpdateInput) {
    const keys = [
        "a",
        "b"
    ] as const;
    for (const key of keys) {
        updateKey(target, inbound, key);
    }
}

方案3:用 Object.assign 简化逻辑

如果不需要逐个判断属性是否存在,直接用 Object.assign 合并非 undefined 属性,TypeScript 能自动处理类型兼容:

function RETURN () {
    return {
        a : "name",
        b : 1,
        id : "any"
    }
}
type UpdateInput = {
    a ?: string,
    b ?: number
}
function UPDATE (target : ReturnType<typeof RETURN>, inbound : UpdateInput) {
    Object.assign(target, inbound);
}

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 02:20:14