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

收集属性名到数组时触发TypeScript TS2345错误的问题求助

问题描述

以下更新后的简化代码展示了问题:

type BaseCol<TCol> = TCol & {
    syncProps?: Exclude<keyof BaseCol<TCol>, "syncProps">[];
    width?: number;
    text: string;
}

function createProperty<
    TColumn extends BaseCol<ExtraProps>,
    ExtraProps
>(column: TColumn, prop: Exclude<keyof TColumn, "syncProps">) {
    const x = column[prop];
    column.syncProps ??= [];
    column.syncProps.push(prop); // <--- TS2345 错误。
}

createProperty({
    a: 1,
    b: 2,
    width: 1,
    text: 'ABC'
}, 'a'); // <--- 智能提示正常工作。

基础类型BaseCol<TCol>是供Svelte组件使用者定义列列表的类型。TCol类型参数用于扩展列的属性,以满足业务需求。

createProperty函数旨在创建任意属性的「可同步」版本(具体实现未展示),并将属性名记录到列的syncProps属性中。

根据定义,createProperty的第二个参数是「列的所有属性,除了控制属性」(此处仅展示syncProps一个),因此syncProps本身的类型定义也是完全一致的。

注意:本问题最初的代码片段未在createProperty中定义第二个类型参数(ExtraProps),而是让第一个类型参数继承自BaseCol<Record<string, any>>,相关注释提及该情况的原因即在于此。

示例用例:

type MyColumn = BaseCol<{ a: string; b: number; }>;

const cols: MyColumn[] = [
    ...
];

createProperty(cols[3], 'width');

内容的提问来源于stack exchange,提问作者José Ramírez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:13:19