Skip to content

feat: 优化FilterUnknownType工具类 #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 12, 2025

Conversation

busy-dog
Copy link
Contributor

@busy-dog busy-dog commented Jun 11, 2025

改进 FilterUnknownType<T> 类型定义的精确性

🔍 问题描述

原来的 FilterUnknownType<T> 实现过于粗暴:

type FilterUnknownType<T> = string extends keyof T ? {} : T

当类型 T 包含字符串索引签名时,会直接返回空对象 {},这导致所有已知的字面量属性也被过滤掉了

✨ 解决方案

新的实现更加精确:

type FilterUnknownType<T> = {
    [P in keyof T as string extends P ? never : P]: T[P]
}

这个实现会:

  1. 遍历类型 T 的每个属性键 P
  2. 对于字符串索引签名(string extends Ptrue),将其过滤为 never
  3. 对于具体的字面量属性键,保留原始类型 T[P]

🎯 改进效果

以一个混合类型为例:

type Mixed = { name: string; age: number; [key: string]: any }

// 原实现结果:{}
// 新实现结果:{ name: string; age: number }

💡 意义

新实现能够精确地只过滤掉未知的动态属性,同时保留所有已知的字面量属性,这对于微信小程序组件的类型安全更加重要,确保开发者能够正确访问到组件的已知属性,而不会因为存在字符串索引签名就丢失所有类型信息。

@SgLy
Copy link
Member

SgLy commented Jun 11, 2025

能同时在 issue.test.ts 中再添加一个原来的实现无法通过,只有新实现能通过的自动化测试用例吗?

@busy-dog
Copy link
Contributor Author

能同时在 issue.test.ts 中再添加一个原来的实现无法通过,只有新实现能通过的自动化测试用例吗?

Done

@SgLy SgLy merged commit 6a85798 into wechat-miniprogram:master Jun 12, 2025
1 check passed
@busy-dog busy-dog deleted the feat/filter-unknown-type branch June 12, 2025 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants