如何让TypeScript函数返回精确IUserDto类型,无额外属性?
解决TypeScript函数返回精确类型的问题
TypeScript的结构类型系统默认允许返回包含额外属性的对象,只要满足目标类型的所有属性就会被认为兼容。要强制检测额外属性,有以下几种可行方案:
方案1:用工具类型约束额外属性为never
定义一个Exact工具类型,将额外属性标记为never,一旦存在就触发类型错误:
type Exact<T, U> = T & Record<Exclude<keyof U, keyof T>, never>; interface IUserModel{ fullname: string username: string password: string } type IUserDto = Omit<IUserModel, 'password'> function createUser(user: IUserModel): Exact<IUserDto, typeof newUser> { const newUser: IUserModel = { fullname: user.fullname, username: user.username, password: user.password } // 此时TypeScript会报错,提示password属性不符合never类型要求 return newUser as Exact<IUserDto, typeof newUser>; }
方案2:利用satisfies保留精确字面量类型
用satisfies关键字让变量符合IUserModel结构,但保留其精确的字面量类型,返回时就能检测到多余属性:
interface IUserModel{ fullname: string username: string password: string } type IUserDto = Omit<IUserModel, 'password'> function createUser(user: IUserModel): IUserDto { const newUser = { fullname: user.fullname, username: user.username, password: user.password } satisfies IUserModel; // 报错:存在多余的password属性,无法赋值给IUserDto return newUser; }
方案3:用泛型辅助函数做严格检查
封装一个泛型函数,强制传入的参数必须严格匹配目标返回类型:
interface IUserModel{ fullname: string username: string password: string } type IUserDto = Omit<IUserModel, 'password'> function strictReturn<T>(obj: T): T { return obj; } function createUser(user: IUserModel): IUserDto { const newUser: IUserModel = { fullname: user.fullname, username: user.username, password: user.password } // 报错:IUserModel类型无法赋值给IUserDto类型 return strictReturn<IUserDto>(newUser); }
内容的提问来源于stack exchange,提问作者Franco
相关产品推荐
相关产品推荐

