首页 > 解决方案 > 当指定同级泛型时,根据传递的数据保留泛型类型,而不是默认值

问题描述

在单元测试中,我不需要非常严格,我想要一个允许我跳过类型转换的动态泛型类型。

我想T成为任何东西,但如果我指定它 - 我应该得到确切的类型。

无论是否指定了 T,我都想R成为 的类型。params

问题是 - 一旦我指定T,我必须指定R,我添加了它的默认值{ [key: string]: any },但它破坏了类型并且不尊重正确params的类型。

declare function test<T, R extends { [key: string]: any } = { [key: string]: any }>(
  template: string,
  params: R,
): {t: T, r: R};

// test without specified generics
const test1 = test('f', {
  a: 'a',
});

test1.t; // as expected - unknown, because I didn't specify it.
test1.r.a; // as expected - works, it's a string
test1.r.b; // as expected - fails, it doesn't exist

// test with a specified generic
const test2 = test<string>('f', {
  a: 'a',
});

test2.t; // as expected - string
test2.r.a; // failed - it's any, not string anymore
test2.r.b; // failed - it's any, not forbidden anymore

// I'm trying kind of
declare function anotherTest<T>(
  template: string,
  params: { [key: string]: any },
): {t: T, r: typeof params}; // I want the passed type, not { [key: string]: any }

我想如果不将参数作为自变量移动并指定其类型,就没有办法做到这一点,也许你知道一个解决方案。提前致谢!

TS游乐场

标签: typescript

解决方案


目前这是不可能的,但好消息是它正在开发中:

https://github.com/microsoft/TypeScript/issues/10571 https://github.com/microsoft/TypeScript/pull/26349

一个可能的解决方案是这样的:领导infer就是魔法。

type TypeConstraint = string | boolean;
function getName<A, infer B extends TypeConstraint>(a: A, b: B): B {}

// ok
const abc: boolean = getName<string>("abc", true);
const abc: boolean = getName<string, boolean>("abc", true);

// error
const abc: boolean = getName<string>("abc", 10);

推荐阅读