Typescript如何为interface中未定义的属性设置默认类型
TypeScript 实现未定义属性默认指定类型的方案
TypeScript 原生不支持你示例中写的[default]语法,要实现「显式声明过的属性保留原有类型,其余未声明属性统一为指定类型」的效果,可以用类型别名+交叉类型+泛型工具的方案实现:
前置准备
先定义你业务中依赖的基础类型:
// 示例依赖类型,可替换为你实际的类型定义 type Instance = { /* Instance 类型的实际逻辑 */ } type Signal = { /* Signal 类型的实际逻辑 */ }
实现步骤
- 首先定义所有需要显式声明的属性结构:
interface DefinedProps { Parent: Instance, Name: string, __Connections: { [x: string]: Signal }, Children: { [x: string]: Instance }, Creatable: true, }
- 组合生成最终类型,让未显式声明的属性默认类型为
Instance:
type MyInterface = DefinedProps & Record<Exclude<string, keyof DefinedProps>, Instance>
代码解释
keyof DefinedProps会获取所有显式声明的属性名联合:"Parent" | "Name" | "__Connections" | "Children" | "Creatable"Exclude<string, keyof DefinedProps>表示排除上述显式属性名之外的所有字符串类型键Record<Exclude<...>, Instance>约束所有非显式声明的属性,类型必须为Instance- 用
&交叉符号把显式属性约束和默认属性约束结合,就得到了你要的效果
效果测试
const validDemo: MyInterface = { Parent: {} as Instance, Name: "demo", __Connections: {}, Children: {}, Creatable: true, // 额外未声明属性,类型为Instance就合法 CustomProp: {} as Instance } const invalidDemo: MyInterface = { Parent: {} as Instance, Name: "demo", __Connections: {}, Children: {}, Creatable: true, // 报错:string 类型不能赋值给 Instance 类型 CustomProp: "test" }
通用工具类型封装
如果你多个场景需要用到这个能力,可以封装成通用的泛型工具类型复用:
type WithDefaultPropType<Defined extends object, DefaultType> = Defined & Record<Exclude<string, keyof Defined>, DefaultType> // 使用时直接传入显式属性类型和默认类型即可 type MyInterface = WithDefaultPropType<DefinedProps, Instance>
内容的提问来源于stack exchange,提问作者TypeChecked
相关产品推荐
相关产品推荐

