最近写稍微复杂点的组件,发现 TS 的知识储备不够用,很多复杂的类型不好定义,花费了太多时间在 ts 上。 比如
export type Field =
| IFieldText
| IFieldSingleSelect
type IFieldText = {
type: 'text'
}
type IFieldSingleSelect = {
type: 'single_select'
// 选项
options: ISelectOption[]
}
此时我想定义一个表单,表单的 key 为 Field 联合类型中可能存在的 key ,此时会报 options 不存在
type form:Field = { type: "", options: "" }
还有表单的数据类型根据 field.type 进行变化等等 这种稍微复杂点的就抓耳挠腮,augment 写的也不好
有没有更方便解决这种问题的办法
![]() |
1
weixind 22 天前 ![]() 建议你先通过 AI 学习一下 TS 类型推断相关的内容,当你有一定思路的时候,再结合 AI ,该问题的答案就手到擒来。
或者先玩下 type challenges "要用 AI 替代你的手,不要用 AI 替代你的脑子。” —— 莎士比亚 |
![]() |
2
andyskaura 22 天前
type form:Field 这是啥写法
|
3
Dorathea 22 天前
看起来你需要 Mapped types?
https://www.typescriptlang.org/docs/handbook/2/mapped-types.html |
![]() |
4
Flands OP @andyskaura 打错了,const..
|