问题描述
我试图弄清楚条件类型的工作原理,但似乎我没有正确理解某些东西。
type SchemaOne = {
[key: string]: {
schemaOnePropOne: string;
schemaOnePropTwo: string;
};
}
type SchemaTwo = {
[key: string]: {
schemaTwoPropOne: string;
schemaTwoPropTwo: string;
};
}
我需要将它们转换为这种格式:
type TransformedSchemaOne = {
title: string;
schemaOnePropOne: string;
schemaOnePropTwo: string;
}
type TransformedSchemaTwo = {
title: string;
schemaTwoPropOne: string;
schemaTwoPropTwo: string;
}
所以我可以使用这样的函数:
const transformSchemas = <T extends Schemas>(obj: T): ExtractReturnedType<T>[] => {
const keys = Object.keys(obj);
const newObj = keys.map(key=> ({title: key,...obj[key]}))
return newObj;
}
这会给我
[{ "title": "title","schemaOnePropOne": "一","schemaOnePropTwo": "两个" }]
现在我想为该函数引入类型,因此我从一个 API 创建了模式的联合
type Schemas = SchemaOne | SchemaTwo;
和提取返回值的条件类型:
type ExtractReturnedType<S> = S extends SchemaOne ? TransformedSchemaOne : S extends SchemaTwo ? TransformedSchemaTwo : never;
当我使用特定模式进行测试时,这似乎有效:
// no type errors
const testOne:ExtractReturnedType<SchemaOne>[] = [{
schemaOnePropOne: 'string;',schemaOnePropTwo: 'string;',title: 'string;',}]
// no type errors
const testTwo:ExtractReturnedType<SchemaTwo>[] = [{
schemaTwoPropOne: 'string;',schemaTwoPropTwo: 'string;',}]
const transformSchemas = <T extends Schemas>(obj: T): ExtractReturnedType<T>[] => {
const keys = Object.keys(obj);
const newObj = keys.map(key=> ({title: key,...obj[key]}))
// Type '({ schemaOnePropOne: string; schemaOnePropTwo: string; title: string; } | { schemaTwoPropOne: string; schemaTwoPropTwo: string; title: string; })[]' is not assignable to type 'ExtractReturnedType<T>[]'.
// Type '{ schemaOnePropOne: string; schemaOnePropTwo: string; title: string; } | { schemaTwoPropOne: string; schemaTwoPropTwo: string; title: string; }' is not assignable to type 'ExtractReturnedType<T>'.
// Type '{ schemaOnePropOne: string; schemaOnePropTwo: string; title: string; }' is not assignable to type 'ExtractReturnedType<T>'.(2322)
return newObj;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)