TypeScript如何定义含动态键与指定键的类型并在interface泛型中使用
问题原因
错误的核心原因是定义interface泛型时漏写了extends约束关键字,导致TypeScript无法识别你对ItemInterface的类型限制,还是会触发索引签名的兼容性校验。
正确写法
首先修正interface的泛型声明,和之前的函数泛型逻辑保持对齐:
export type VerifyT<T> = { disabled?: boolean } & { [K in keyof T]: K extends "disabled" ? unknown : string | number }; // 给泛型参数加上extends关键字声明约束 export interface Test<ItemInterface extends VerifyT<ItemInterface>> { items: ItemInterface }
使用示例
// 显式传入类型参数 const demo: Test<{ label: string, key: number, disabled?: boolean }> = { items: { label: 'Option 2', key: 2, disabled: true } }; // 也可以配合satisfies让TS自动推导类型,不需要手动传参 const autoDemo = { items: { iconName: 'person_outline', label: 'Option 2', key: 2, disabled: true } } satisfies Test<typeof autoDemo.items>;
可选简化方案
如果不需要严格限制除disabled外的其他键不能是布尔值,也可以直接写更简单的交叉类型,不需要用递归泛型约束:
export type Item = { disabled?: boolean, } & { [k: string]: string | number | boolean | undefined }; export interface Test { items: Item }
内容的提问来源于stack exchange,提问作者Nouh Belahcen
相关产品推荐
相关产品推荐

