

























这是一个创建于 866 天前的主题,其中的信息可能已经有所发展或是发生改变。
需求: 一个类型必须包含 id 属性,值的类型为 string ,同时它可能包含其他的属性,但值的类型必须是 number 。
第 1 条附言 · 2024 年 1 月 30 日
其实只提示类型的话,大家给出了答案。问题出在初始化上:
需求场景也很简单,我有一个列表,这个列表每一行有一个 id ,是 string 的。
但是其他的属性都是 number 。
const data: Item = {
id: 'xxx-xxx-xxx', // id 只能是 string
cid: 123123123,
name: 233233,
...//任意属性,但值必须是 number 不能是其他的或者 string
}
第 2 条附言 · 2024 年 1 月 30 日
折中玩法
const id = Symbol('id');
type CustomType = {
[t: string]: number
[id: symbol]: string
}
const data:CustomType = {
[id]: '123123xxx123',
v2: 123233
}
1 nomagick 2024 年 1 月 30 日```typescript ``` |
2 liahu 2024 年 1 月 30 日{ |
3 simoger 2024 年 1 月 30 日interface MyObject { |
4 lilei2023 2024 年 1 月 30 日这不是有三位热心网友帮你实现了一个么? |
5 cvooc 2024 年 1 月 30 日这种? ```ts |
7 cvooc 2024 年 1 月 30 日明白你意思了, 我理解问题, 1 楼是对的 |
8 cvooc 2024 年 1 月 30 日你不妨 给个具体示例, 看你回复上面都不对完全不理解什么意思了 |
9 wednesdayco 2024 年 1 月 30 日@retrocode 1 楼也不对 |
10 wednesdayco 2024 年 1 月 30 日@liahu 其他的属性值的类型必须是 number ,除了属性 id 的值的类型必须是 string |
12 Bologna 2024 年 1 月 30 日放一个数据样例更好解决问题 |
13 tearzx 2024 年 1 月 30 日interface A{ interface B { type C = A | B; |
14 nomagick 2024 年 1 月 30 日还真是,等一个答案 |
16 wednesdayco 2024 年 1 月 30 日@MRG0 const data: IData = { |
17 Pencillll 2024 年 1 月 30 日 via Android实现不了,因为没有办法把 'id' 从 string 里面排除出来 |
18 fannheyward 2024 年 1 月 30 日#3 是对的 ``` |
20 rrfeng 2024 年 1 月 30 日string indexer MUST accommodate all members |
21 nomagick 2024 年 1 月 30 日我解开了 interface NumO { type WithID<T> = { const v = { // OK |
22 ntdll 2024 年 1 月 30 日interface A { interface B { type AB = A & B function sample(arg: AB) { |
24 nomagick 2024 年 1 月 30 日再加一个类型参数,现场合并。。。 |
26 NoManPlay 2024 年 1 月 30 日``` // 通过映射类型和条件类型来移除 id 属性外的 string 类型 |
28 Pencillll 2024 年 1 月 30 日对于初始化来说,如果可以加个 helper 函数的话,倒是有一种办法: type CoercedItem<T> = { type ValidItem<T> = T extends CoercedItem<T> ? 'id' extends keyof T ? T : never : never function makeItem<T>(item: ValidItem<T>): T { const a = makeItem({ id: 'x', no: 1 }) const b = makeItem({ id: 'z' }) // 报错 // 报错 |
29 Pencillll 2024 年 1 月 30 日不过上面这样有个缺陷是初始化之后的对象不能再添加新的属性 |
30 CLMan 2024 年 1 月 30 日好奇什么场景需要这么复杂的类型定义呢? 或者说类似问题的类型约束的严谨性和代码简洁应该如何取舍? 我个人是把 TS 当作一个不太完美的类型约束工具,更倾向于代码简洁性。 |
31 Gaoti 2024 年 2 月 1 日```ts type T<O = Others> = { const obj: T<{ id: string; aaa: number }> = { 使用的时候泛型传入对应的类型就行,但是和 #28 说的一样,泛型中没有定义的的字段会报错 |
32 chnwillliu 2024 年 3 月 13 日 via Androidconst id = ()=> ('i' + 'd ').trim(); const n:number = obj[id()]; 如果有这样的类型你这样操作那 TS 该不该报错? key 是运行时决定,所以有可能是 string 也有可能是 number 。 |
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。