Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript:是否可以将泛型类型计算为字符串文字?_Typescript - Fatal编程技术网

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结果,它现在传播类型