Typescript 为什么我可以创建一个具有字符串文本的对象,但如果有泛型,我可以';T
我尝试创建一个具有字符串文字的对象Typescript 为什么我可以创建一个具有字符串文本的对象,但如果有泛型,我可以';T,typescript,Typescript,我尝试创建一个具有字符串文字的对象 导出类型MyType={ propFromMyType:T; }; 导出类型TypeWithGenericLiteral={ [P在`${T}u中加上``字面值`]:数字; }; 如果我的create函数本身不使用泛型类型,则它可以正常工作: const create=(t:MyType):TypeWithGenericLiteral=>{ const prop=`${t.propFromMyType}}u,其中_literal`作为const; 返回{
导出类型MyType={
propFromMyType:T;
};
导出类型TypeWithGenericLiteral={
[P在`${T}u中加上``字面值`]:数字;
};
如果我的create函数本身不使用泛型类型,则它可以正常工作:
const create=(t:MyType):TypeWithGenericLiteral=>{
const prop=`${t.propFromMyType}}u,其中_literal`作为const;
返回{
[道具]:777
};
}
但是,如果create函数本身包含一个类型T,则它正在崩溃:
const create=(t:MyType):TypeWithGenericLiteral=>{
const prop=`${t.propFromMyType}}u,其中_literal`作为const;
返回{
[道具]:777
};
}
即使我将类型T更改为这样的特定文字,它也不起作用:
键入action=“example”
导出类型MyType={
propFromMyType:T;
};
导出类型TypeWithGenericLiteral={
[P在`${T}u中加上``字面值`]:数字;
};
const create=(t:MyType):TypeWithGenericLiteral=>{
const prop=`${t.propFromMyType}}u,其中_literal`作为const;
返回{
[道具]:777
};
}
这是因为不可能知道将使用哪个类型参数调用函数。请看以下示例:
const propFromMyType: 'example' | 'foo' = 'example';
create2({ propFromMyType })
预期结果类型为:
type ResultType = TypeWithGenericLiteral<'example' | 'foo'>
// { example_with_literal: number; foo_with_literal: number; }
type ResultType=TypeWithGenericLiteral
//{example_with_literal:number;foo_with_literal:number;}