我首先使用对象键生成建议键,如下所示
const data = {
content: {
value: "string",
},
anotherContent: {
anotherValue: 20
}
}.
const result = function(["content.value","anotherContent.anotherValue"])
首先,我希望result
的型号是{value: number, otherValue: number}
.
所以,我这样打字.
<Target, Suggestion extends DotedKeysType<S>[]>(
target?: Target extends Suggestion ? Target : Suggestion
): {
[key in Target extends Suggestion ? Target[number] : string]: Target extends Suggestion
? OutputByKeys<S, key>
: never;
};
除以下各项外,其他各项运行正常.
- 当目标是
content
时,我可以按如下方式使用它
<View>{result.content}</View>
- 当它是
anotherContent.anotherValue
的时候,我必须像这样使用它.
<View>{result["anotherContent.anotherValue"]}</View>
我也意识到,即使我们成功了,我们也会有一个关键的问题
// for a data like this. Both last keys are named 'value'
const data = {content: {value: 10},anotherContent: {value: 20}}
// Keeping the result as an object override the value key in the object.
// Since objects can not have same key as property
const result = function(["content.value","anotherContent.value"]);
result = {value : 20 // `Override value of content with anotherContent`}
但是使用数组的结果是,数组中的每个项可以有不同的名称.例如
result = [myFirstValue, mySecondValue] = function(["content.value","anotherContent.anotherValue"])
其中,myFirstValue
的类型必须是content.value
的类型,而mySecondValue
的类型必须是anotherContent.anotherValue
的类型.
到目前为止,这就是我所做的一切.
<Target, Suggestion extends DotedKeysType<S>[]>(
target?: Target extends Suggestion ? Target : Suggestion
): OutputByKeys<S, Target extends Sug ? Target[number] : keyof S>[];
这为我提供了目标数组中所有键的联合类型.
result = [value1: string | number, value2: string | number]
Is there a way to get a type like this in case of array?个
// type of `content.value` is `string`
// type of `notherContent.anotherValue` is `number`
const result = function(["content.value","anotherContent.anotherValue"]);
result => [myFirstValue, mySecondValue]
result type will be [value1: string, value2: number]
And in case of object where last key are different个
// type of `content.value` is `string`
// type of `anotherContent.anotherValue` is `number`
const result = function(["content.value","anotherContent.anotherValue"])
result => {value: "string", anotherValue: 20}
result type => {value: string, anotherValue: number}
如果可能的话,我不想要十字路口.
// i don't want that if possible
result type => [string & number, string & number]
但我想要这个
result type => [string, number]
我无法预测用户的 Select ,否则我只需将数组类型设置为=> [string, number]
,我的问题就解决了.我已经读了很多答案,但我仍然没有找到我需要的.
我以不同的方式要求同样的东西.对象,因为它可能在另一个项目中有用,而数组,因为它是我当前需要的.