泛型typescript函数,用于验证对象的键是否为字符串



这是我想写的函数,但我无法让泛型正常工作。

正如你所看到的,我想返回T[K]绝对是一个字符串,关键是能够使用它

a = {key: "unknown type"};
if (!validateRequiredStringKey(a, "key")) {
return
}
// Here we should know that a.key is a string
funcThatTakesAString(a.key);
export const validateRequiredStringKey = <
T,
K extends keyof T & (string | number)
>(
obj: T,
key: K
): obj is T & { [K]: string } => {
const v = obj[key];
if (!(typeof v === "string")) {
throw new ValidationError(`${key} is not a string`);
}
if (v === "") {
throw new ValidationError(`${key} is empty`);
}
return true;
};

tsc的错误为

src/domain/validations/utils.ts:12:17 - error TS1170: A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.
12 ): obj is T & { [K]: string } => {
~~~
src/domain/validations/utils.ts:12:18 - error TS2693: 'K' only refers to a type, but is being used as a value here.
12 ): obj is T & { [K]: string } => {

我还没有彻底检查validateRequiredStringKey的定义,但您可以通过用{[Key in K]: string}或仅用Record<K, string>替换{ [K]: string }来使其工作。

TypeScript游乐场