如何枚举接口键以创建新的接口,其值依赖于键。

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

How to enumerate interface keys to make new interface that the value is depend on the key

问题

type IParse<T> = {
    [K in keyof T as K extends string ? K : never]: string // 如何使得当 K === 'a' 时,类型应为 number
}

interface X {
    a: number
    b: string
    c: string[]
    d: number[]
}

type Result = IParse<X>;

// 实际结果

interface Actual {
    a: string
    b: string
    c: string
    d: string
}

// 期望结果

interface Expected {
    a: number
    b: string
    c: string
    d: string
}
英文:

How to iterate interface keys to make new interface that the value is depend on the key.

type IParse&lt;T&gt; = {
	[K in keyof T as K extends string ? K : never]: string // How to make if K === &#39;a&#39; the type should be number
}

interface X {
	a: number
	b: string
	c: string[]
	d: number[]
}

type Result = IParse&lt;X&gt;

// Actual result

interface Actual {
    a: string
    b: string
    c: string
    d: string
}

// Expected result

interface Expected {
    a: number
    b: string
    c: string
    d: string
}

Playground

答案1

得分: 1

你可以通过在你已有的值部分添加一个条件来实现:

type IParse&lt;T&gt; = {
	[K in keyof T as K extends string ? K : never]: 
        K extends &quot;a&quot; ? number : string; // &lt;======================
};

interface X {
	a: number;
	b: string;
	c: string[];
	d: number[];
}

type Result = IParse&lt;X&gt;;
//   ^? -- type Result = {a: number; b: string; c: string; d: string; }

Playground链接

英文:

You can do it by adding a conditional to the value portion of what you have:

type IParse&lt;T&gt; = {
	[K in keyof T as K extends string ? K : never]: 
        K extends &quot;a&quot; ? number : string; // &lt;======================
};

interface X {
	a: number;
	b: string;
	c: string[];
	d: number[];
}

type Result = IParse&lt;X&gt;;
//   ^? -- type Result = {a: number; b: string; c: string; d: string; }

Playground link

huangapple
  • 本文由 发表于 2023年5月24日 21:35:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324134.html
匿名

发表评论

匿名网友

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

确定