有办法吗?我知道,我可以 if/else 或切换我的“type”属性来获取特定的接口(interface)。但是我可以用函数(或方法)的返回值来制作类似的东西吗?
interface test1 {
type: 'test1'
}
interface test2 {
type: 'test2'
}
type unType = test1 | test2;
//i know property "type"'s value
//can i somehow use this information to infer specific type (test1 or test2)
function whichType<T>(typeValue): T {
return null;
}
const tt1 = whichType<unType>('test1');// should be interface test1
const tt2 = whichType<unType>('test2');// should be interface test2
最佳答案
您可以按照 TJ Crowder 的建议使用重载,如果您只有几个接口(interface),这可能是最好的解决方案,因为编写理解很简单。
更通用的解决方案是使用 Extract
条件类型根据传入的字符串提取类型:
interface test1 { type: 'test1' }
interface test2 { type: 'test2' }
type unType = test1 | test2;
function whichType<K extends unType['type']>(typeValue: K): Extract<unType, {type: K}> {
return null!;
}
const tt1 = whichType('test1'); // test1
const tt2 = whichType('test2'); // test2
可以构建适用于任何联合的解决方案,但它要求您使用函数柯里化(Currying),因为 typescript 不支持部分类型参数推断:
function whichType<T extends { type: string}>() {
return function <K extends T['type']>(typeValue: K): Extract<T, {type: K}> {
return null!;
}
}
const tt1 = whichType<unType>()('test1'); // test1
const tt2 = whichType<unType>()('test2'); // test2
关于typescript - 推断函数返回类型,了解一个属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55989937/