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

Typescript如何为interface中未定义的属性设置默认类型

TypeScript 实现未定义属性默认指定类型的方案

TypeScript 原生不支持你示例中写的[default]语法,要实现「显式声明过的属性保留原有类型,其余未声明属性统一为指定类型」的效果,可以用类型别名+交叉类型+泛型工具的方案实现:

前置准备

先定义你业务中依赖的基础类型:

// 示例依赖类型,可替换为你实际的类型定义
type Instance = { /* Instance 类型的实际逻辑 */ }
type Signal = { /* Signal 类型的实际逻辑 */ }

实现步骤

  1. 首先定义所有需要显式声明的属性结构:
interface DefinedProps {
  Parent: Instance,
  Name: string,
  __Connections: {
    [x: string]: Signal
  },
  Children: {
    [x: string]: Instance
  },
  Creatable: true,
}
  1. 组合生成最终类型,让未显式声明的属性默认类型为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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:24:02