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

如何在TypeScript中为指定类型变量获取所有键类型

解决方案:保留具体键类型同时约束结构符合类型A

方案一:使用satisfies关键字(TypeScript 4.9+推荐)

satisfies关键字可以让变量的结构符合指定类型约束,同时保留自身的具体类型信息,不会被宽泛的索引签名覆盖。

type A = {
    [key: string]: {
        value: any;
        validate: string;
        error: null | string;
        required?: boolean;
    };
};

// 用satisfies约束b符合A的结构,同时保留具体键的类型
let b = {
    name:{value:"", error:null, validate:"required"},
    email:{value:"", error:null, validate:"required"}
} satisfies A;

// 成功获取具体键类型
type B = keyof typeof b; // "name" | "email"

// 基于B生成类型D
type D = {
    [key in B]: {
        value: any;
        validate: string;
        error: null | string;
        required?: boolean;
    };
};

方案二:泛型函数辅助推导(兼容低版本TypeScript)

如果项目使用的TypeScript版本低于4.9,无法使用satisfies,可以通过泛型函数实现类型约束与具体键保留:

type A = {
    [key: string]: {
        value: any;
        validate: string;
        error: null | string;
        required?: boolean;
    };
};

// 泛型函数约束传入对象必须符合A的结构,同时推导并返回具体类型
function createFormObj<T extends A>(obj: T): T {
    return obj;
}

// 通过函数创建b,既保证结构合法,又保留具体键类型
let b = createFormObj({
    name:{value:"", error:null, validate:"required"},
    email:{value:"", error:null, validate:"required"}
});

type B = keyof typeof b; // "name" | "email"

type D = {
    [key in B]: {
        value: any;
        validate: string;
        error: null | string;
        required?: boolean;
    };
};

内容的提问来源于stack exchange,提问作者Soumen Khara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:33:27