英文:
Is there a way to have mapped types and a specific property?
问题
我有一个类似这样的想法:
```ts
type Foo<T, K extends string> = K extends "isDirty"
? never
: {
[P in K]: T;
isDirty: boolean;
};
但是 TypeScript 仍然不知道 K
永远不会是 "isDirty"
。
我想做的是,允许任何键值,所以它可以是 foo
、bar
、potatoes
,并且将其类型设为 T
。但同时也有属性 isDirty: boolean
,这样 K
可以拥有任何值,但不包括这个。
一些示例:
const foo: Foo<number, "bar"> = {
bar: 5,
isDirty: false
}
const potatoes: Foo<number[], "potatoes"> = {
potatoes: [1,6,15],
isDirty: false
}
在 TypeScript 中是否可能实现这样的功能?
<details>
<summary>英文:</summary>
I had in mind something like this:
```ts
type Foo<T, K extends string> = K extends "isDirty"
? never
: {
[P in K]: T;
isDirty: boolean;
};
But Typescript still doesn't know that K
will never be `"isDirty".
What I wanted to do is, allow any key value, so it could be foo
, bar
, potatoes
and have that be of type T
. But also have the property isDirty: boolean
, so K
can have any value but that.
Some examples:
const foo: Foo<number, "bar"> = {
bar: 5,
isDirty: false
}
const potatoes: Foo<number[], "potatoes"> = {
potatoes: [1,6,15],
isDirty: false
}
Is this possible to do in Typescript?
答案1
得分: 1
You can use an intersection of {[P in K]: T}
and {isDirty: boolean}
:
type Foo<T, K extends string> = K extends "isDirty"
? never
: {
[P in K]: T;
} & {
isDirty: boolean;
};
const foo: Foo<number, "bar"> = {
bar: 5,
isDirty: false,
};
const potatoes: Foo<number[], "potatoes"> = {
potatoes: [1, 6, 15],
isDirty: false,
};
英文:
You can use an intersection of {[P in K]: T}
and {isDirty: boolean}
:
type Foo<T, K extends string> = K extends "isDirty"
? never
: {
[P in K]: T;
} & {
isDirty: boolean;
};
const foo: Foo<number, "bar"> = {
bar: 5,
isDirty: false,
};
const potatoes: Foo<number[], "potatoes"> = {
potatoes: [1, 6, 15],
isDirty: false,
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论