typescript - 为什么我可以使用字符串文字创建一个对象,但如果泛型到位,我不能?
问题描述
我尝试使用字符串文字创建一个对象。
export type MyType<T extends string> = {
propFromMyType: T;
};
export type TypeWithGenericLiteral<T extends string> = {
[P in `${T}_with_literal`]: number;
};
如果我的创建函数本身不使用泛型类型,它可以正常工作:
const create = (t: MyType<"example">): TypeWithGenericLiteral<"example"> => {
const prop = `${t.propFromMyType}_with_literal` as const;
return {
[prop]: 777
};
}
但是如果 create 函数本身包含一个类型 T ,它就会分崩离析:
const create = <T extends string> (t: MyType<T>): TypeWithGenericLiteral<T> => {
const prop = `${t.propFromMyType}_with_literal` as const;
return {
[prop]: 777
};
}
即使我将类型 T 更改为这样的特定文字,它也不起作用:
type action = "example"
export type MyType<T extends action> = {
propFromMyType: T;
};
export type TypeWithGenericLiteral<T extends action> = {
[P in `${T}_with_literal`]: number;
};
const create = <T extends action> (t: MyType<T>): TypeWithGenericLiteral<T> => {
const prop = `${t.propFromMyType}_with_literal` as const;
return {
[prop]: 777
};
}
解决方案
这是因为无法知道函数将使用哪个类型参数调用。看看下面的例子:
const propFromMyType: 'example' | 'foo' = 'example';
create2({ propFromMyType })
预期的结果类型将是:
type ResultType = TypeWithGenericLiteral<'example' | 'foo'>
// { example_with_literal: number; foo_with_literal: number; }
推荐阅读
- javascript - 按索引删除 localStorage vuejs 数组中的文章
- arrays - 如何在 Rust 中直接在堆上创建巨大的数组,跳过堆栈?
- amazon-s3 - 正则表达式组匹配文件中的每条记录,其中换行符不是新记录的指示符
- angular - Angular 提供者:使用现有的或创建一个(如果未提供)
- androidpdfviewer - 如何在 Android Studio 中的文档(.pdf、.doc)上添加水印?
- python - 在 Python 中忽略某些用于网页抓取的标签
- c# - 如果两个对象具有所有属性值,则检查对象列表
- php - 如何在 PHP 中正确插入 div?
- pygame - NameError:名称“事件”未定义
- asynchronous - Grails 4 异步与数据库操作