gpt4 book ai didi

typescript 泛型 : Howto map array entries to object keys

转载 作者:行者123 更新时间:2023-12-03 23:10:58 24 4
gpt4 key购买 nike

TLDR:在我的通用功能中,我想要myFunction(['width', 'left'])返回类型 {width: string, left: string} .

长版:

我有一个 Typescript 函数,它有一个字符串数组作为输入,并以数组的键作为值返回一个对象:

export interface Dictionary<T> {
[index: string]: T | undefined;
}
var getStyle = function (
element: Element,
propertyNames: readonly string[]
) {
let gCS= window.getComputedStyle(element)
let result: Dictionary<string> = {};
propertyNames.forEach((prop)=>{
result[prop]=gCS.getPropertyValue(prop);
});
return result;
};

typescript 返回值是一个对象/字典,但没有特定的属性。
var resultObj = getStyle(document.body, ['width']);
resultObj.width; // should be ok
resultObj.height; // should be not ok

我尝试了很多东西。最好的事情是:
export type RestrictedDictionary1<T, P extends readonly string[]> = {
[index in keyof P]?: T | undefined
}
declare function getStyle1<P extends readonly string[]>(
element: Element,
propertyNames: P
): RestrictedDictionary1<string, P>;

var resultObj1 = getStyle1(document.body, ['width']); // Huh? Why an array
resultObj1.width; // should be ok, but both are unvalid for TS
resultObj1.height; // should be not ok, but both are unvalid for TS

Typescript 现在从中得到了一个数组。我不知道为什么。

最后一次尝试是 interface ,但 [index in P]部分不起作用
export interface RestrictedDictionary2<T, P extends string[]> {
[index in P]: T | undefined; // A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
}
declare function getStyle2<P extends string[]>(
element: Element,
propertyNames: P
): RestrictedDictionary2<string, P>;

var resultObj2 = getStyle2(document.body, ['width']);
resultObj2.width; // should be ok
resultObj2.height; // should be not ok

最佳答案

您的想法非常接近,但语法有点偏离。如果 Pstring[]然后 keyof P只是数组的成员,而不是值。您可以使用 P[number]获取数组中值的类型。接口(interface)也不能包含映射类型([index in P]: ... 语法),只有类型别名可以(type 定义)。还有一个预定义的映射类型,称为 Record这正是你不需要定义一个新的


var getStyle = function<T extends string> (
element: Element,
propertyNames: readonly T[]
): Record<T, string> {
let gCS= window.getComputedStyle(element)
let result = {} as Record<T, string>;
propertyNames.forEach((prop)=>{
result[prop]=gCS.getPropertyValue(prop);
});
return result;
};
var resultObj = getStyle(document.body, ['width']);
resultObj.width; // should be ok
resultObj.height; // err


Play

关于 typescript 泛型 : Howto map array entries to object keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57510297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com