为什么我可以创建一个带有字符串文字的对象,但如果泛型到位,我就不能?



我尝试创建一个具有字符串文字的Object。


export type MyType<T extends string> = {
propFromMyType: T;
};
export type TypeWithGenericLiteral<T extends string> = {
[P in `${T}_with_literal`]: number;
};

如果我的create函数本身不使用泛型类型,它可以正常工作:


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
};
} 

ts游乐场

这是因为不可能知道函数将被调用的类型参数。看看下面的例子:

const propFromMyType: 'example' | 'foo' = 'example';
create2({ propFromMyType })

预期结果类型为:

type ResultType = TypeWithGenericLiteral<'example' | 'foo'>
// { example_with_literal: number; foo_with_literal: number; }

相关内容

最新更新