typescript - 当指定同级泛型时,根据传递的数据保留泛型类型,而不是默认值
问题描述
在单元测试中,我不需要非常严格,我想要一个允许我跳过类型转换的动态泛型类型。
我想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 }
我想如果不将参数作为自变量移动并指定其类型,就没有办法做到这一点,也许你知道一个解决方案。提前致谢!
解决方案
目前这是不可能的,但好消息是它正在开发中:
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);
推荐阅读
- python - 将整个数组与来自另一个数组的条目独立地相乘
- javascript - 在游戏中静音和取消静音的问题
- spring-boot - 如何使用文件URI从运行springboot的docker镜像访问本地文件?
- python-3.x - Python - 打开文件并在屏幕上显示
- c# - 如何以不同的速度编写一堆第一人称动画
- material-ui - KeyboardDatePicker 的 Material UI 填充输入
- r - (R) 编辑数据表中多列数据后面单元格的渐变颜色
- angular - ngFor 中调用的方法多次触发
- azure-devops - 获取项目列表及其进程名称
- rest - 如何使用rest api从nuxeo文件夹中获取文件名列表?