确保类型始终从函数参数推断,即使指定了其他类型参数

问题描述 投票:0回答:1

我希望函数的返回类型是基于函数参数值的条件类型。这是最小的复制品:

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..."

TS游乐场

正如预期,

x
的类型是
"is test!"
,但是
y
的类型是
"is not test..."

在我看来,指定类型

T
会导致 TypeScript 将类型
K
泛化为泛型
string
,而不是根据
v
的值来推断它。如何确保
K
始终从
v
推断出来?

typescript typescript-generics
1个回答
0
投票

您的函数存在一些问题,即第一个泛型参数未在任何地方使用。但你可以用它来达到想要的结果:

游乐场

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..."
© www.soinside.com 2019 - 2024. All rights reserved.