这种的类型是不是实现不了(TypeScript)

100 天前
 wednesdayco
需求: 一个类型必须包含 id 属性,值的类型为 string ,同时它可能包含其他的属性,但值的类型必须是 number 。
1510 次点击
所在节点    TypeScript
32 条回复
nomagick
100 天前
```typescript
interface wtf {
id: string;
[k: string]: number;
}

```
liahu
100 天前
{
id: string
[key: string]: any
}
???
simoger
100 天前
interface MyObject {
id: string;
[key: string]: number | string;
}
这种?
lilei2023
100 天前
这不是有三位热心网友帮你实现了一个么?
retrocode
100 天前
这种?

```ts
interface Obj {
id: string
}
interface Somebody extends Obj {
key?: number
}
```
wednesdayco
100 天前
@lilei2023 上面三位都不对
retrocode
100 天前
明白你意思了, 我理解问题, 1 楼是对的
retrocode
100 天前
你不妨 给个具体示例, 看你回复上面都不对完全不理解什么意思了
wednesdayco
100 天前
@retrocode 1 楼也不对
Property 'id' of type 'string' is not assignable to 'string' index type 'number'.ts(2411)
wednesdayco
100 天前
@liahu 其他的属性值的类型必须是 number ,除了属性 id 的值的类型必须是 string
wednesdayco
100 天前
@simoger 除属性 id 的值的类型是 string 之外,其他的值的类型都必须是 number
MRG0
100 天前
放一个数据样例更好解决问题
tearzx
100 天前
interface A{
[key: string]: number;
}

interface B {
id: string;
}

type C = A | B;
nomagick
100 天前
还真是,等一个答案
wednesdayco
100 天前
@tearzx 不能限制 id 的类型,这样 id 可以为 number
wednesdayco
100 天前
@MRG0

const data: IData = {
id: 'xxx-xxx-xxx', // id 只能是 string
cid: 123123123,
name: 233233,
...//任意属性,但值必须是 number 不能是其他的或者 string
}
Pencillll
100 天前
实现不了,因为没有办法把 'id' 从 string 里面排除出来
fannheyward
100 天前
#3 是对的

```
interface IData {
id: string
[k: string]: number | string
}
```
fannheyward
100 天前
@fannheyward 不对,这样其他 key 可以是 string 了
rrfeng
100 天前
string indexer MUST accommodate all members

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1012854

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX