有一种方法可以使用映射类型和特定属性吗?

huangapple go评论58阅读模式
英文:

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"

我想做的是,允许任何键值,所以它可以是 foobarpotatoes,并且将其类型设为 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&lt;T, K extends string&gt; = K extends &quot;isDirty&quot;
  ? 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&lt;number, &quot;bar&quot;&gt; = {
  bar: 5,
  isDirty: false
}

const potatoes: Foo&lt;number[], &quot;potatoes&quot;&gt; = {
  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,
};

Playground link

英文:

You can use an intersection of {[P in K]: T} and {isDirty: boolean}:

type Foo&lt;T, K extends string&gt; = K extends &quot;isDirty&quot;
    ? never
    : {
          [P in K]: T;
      } &amp; {
          isDirty: boolean;
      };

const foo: Foo&lt;number, &quot;bar&quot;&gt; = {
    bar: 5,
    isDirty: false,
};

const potatoes: Foo&lt;number[], &quot;potatoes&quot;&gt; = {
    potatoes: [1, 6, 15],
    isDirty: false,
};

Playground link

huangapple
  • 本文由 发表于 2023年5月13日 18:32:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定