我希望函数的返回类型是基于函数参数值的条件类型。这是最小的复制品:
type R<K extends string> = K extends "test" ? "is test!" : "is not test...";
function D<T, K extends string = string>(v: K): R<K> {
// Type T would be used for something else
// This type cast is just for illustrative purposes
return v as unknown as R<K>;
}
const x = D("test"); // x has type "is test!"
const y = D<string>("test"); // y has type "is not test..."
正如预期,
x
的类型是"is test!"
,但是y
的类型是"is not test..."
。
在我看来,指定类型
T
会导致 TypeScript 将类型 K
泛化为泛型 string
,而不是根据 v
的值来推断它。如何确保 K
始终从 v
推断出来?
您的函数存在一些问题,即第一个泛型参数未在任何地方使用。但你可以用它来达到想要的结果:
type R<D extends any, K extends string> = D extends string ? string : K extends "test" ? "is test!" : "is not test...";
function D<T, K extends string = string>(v: K): R<T, K> {
// Type T would be used for something else
// This type cast is just for illustrative purposes
return v as unknown as R<T, K>;
}
const x = D("test"); // x has type "is test!"
const y = D<string>("test"); // y has type "is not test..."