Typescript:是否可以将泛型类型计算为字符串文字?
是否可以在不显式的情况下将泛型类型求值为字符串文字 下面是我想到的一个例子:Typescript:是否可以将泛型类型计算为字符串文字?,typescript,Typescript,是否可以在不显式的情况下将泛型类型求值为字符串文字 下面是我想到的一个例子: function foo<T>(type: T): { type: T } { return { type }; } // type is { type: string } I would like it to be { type: 'FooBar' } without being explicit const bar = foo('FooBar'); // is it possible no
function foo<T>(type: T): { type: T } {
return { type };
}
// type is { type: string } I would like it to be { type: 'FooBar' } without being explicit
const bar = foo('FooBar');
// is it possible not to do this and get same result?
const fooBar = foo<'FooBar'>('FooBar');
const barFoo = foo('FooBar' as const);
函数foo(类型:T):{type:T}{
返回{type};
}
//类型是{type:string}我希望它是{type:'FooBar'}而不是显式的
常量bar=foo('FooBar');
//有可能不这样做而得到同样的结果吗?
常量fooBar=foo('fooBar');
const barFoo=foo(“FooBar”为const);
我也有点惊讶,它没有传播到foo
函数,而是默认为string
类型
const test='FooBar';
常数barFoo=foo(测试);
但是,当我明确指定类型时,没有问题
const test:'FooBar'='FooBar';
常数barFoo=foo(测试);
这就是我们开始的地方
在foo
函数中稍加修饰:
函数foo(类型:T):{type:T}{
返回{type};
}
常量测试='FooBar';
常数barFoo=foo(测试);
当我查看表达式时,我正在查看intellisense结果,它现在传播类型