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

如何为对象属性设置正确类型?TypeScript类型报错求助

解决TypeScript类型错误的方案

错误原因分析

  1. currentSelectedView可能为null,直接访问其属性会触发空值访问错误。
  2. value的类型boolean | string无法与IView的所有属性类型匹配:比如Type属性是number类型,和value的类型不兼容;即使排除Type,TypeScript也无法保证传入的value和选中属性的类型严格对应。

方案一:支持修改所有属性

使用泛型约束属性键与值的类型对应关系,同时处理currentSelectedView为null的情况:

export interface IView {
    "Name": string,
    "Type": number,
    "IsOnlyCurrentWindow": boolean,
    "IsDefault": boolean,
    "IsShared": boolean,
    "Id": string
}

// 类中的属性与方法实现
public currentSelectedView: IView | null = null;

public setCurrentView(view: IView) {
    this.currentSelectedView = view;
}

public changeCurrentViewData<K extends keyof IView>(changeProperty: K, value: IView[K]) {
    if (!this.currentSelectedView) {
        throw new Error("未选中任何视图");
    }
    this.currentSelectedView[changeProperty] = value;
}

方案二:仅支持修改string/boolean类型的属性

如果不需要修改Type(number类型),可以先定义允许修改的属性键类型,再用泛型约束:

export interface IView {
    "Name": string,
    "Type": number,
    "IsOnlyCurrentWindow": boolean,
    "IsDefault": boolean,
    "IsShared": boolean,
    "Id": string
}

// 筛选出IView中类型为string或boolean的属性键
type StringBooleanKeysOfIView = {
    [K in keyof IView]: IView[K] extends string | boolean ? K : never
}[keyof IView];

// 类中的属性与方法实现
public currentSelectedView: IView | null = null;

public setCurrentView(view: IView) {
    this.currentSelectedView = view;
}

public changeCurrentViewData<K extends StringBooleanKeysOfIView>(changeProperty: K, value: IView[K]) {
    if (!this.currentSelectedView) {
        throw new Error("未选中任何视图");
    }
    this.currentSelectedView[changeProperty] = value;
}

内容的提问来源于stack exchange,提问作者Георгий Барсегян

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:05:31