英文:
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<T> = {
[K in keyof T as K extends string ? K : never]: string // How to make if K === 'a' the type should be number
}
interface X {
a: number
b: string
c: string[]
d: number[]
}
type Result = IParse<X>
// Actual result
interface Actual {
a: string
b: string
c: string
d: string
}
// Expected result
interface Expected {
a: number
b: string
c: string
d: string
}
答案1
得分: 1
你可以通过在你已有的值部分添加一个条件来实现:
type IParse<T> = {
[K in keyof T as K extends string ? K : never]:
K extends "a" ? number : string; // <======================
};
interface X {
a: number;
b: string;
c: string[];
d: number[];
}
type Result = IParse<X>;
// ^? -- type Result = {a: number; b: string; c: string; d: string; }
英文:
You can do it by adding a conditional to the value portion of what you have:
type IParse<T> = {
[K in keyof T as K extends string ? K : never]:
K extends "a" ? number : string; // <======================
};
interface X {
a: number;
b: string;
c: string[];
d: number[];
}
type Result = IParse<X>;
// ^? -- type Result = {a: number; b: string; c: string; d: string; }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论