【发布时间】:2021-10-05 12:27:00
【问题描述】:
我有一个函数,它接收一个使用可区分联合的对象,该联合根据该属性返回不同的结构。
虽然我可以写一个断言isLicenseType fn,但我想知道是否有一种方法可以根据提供给 fn 的类型参数(可能带有断言签名)来推断这一点?
const licenseTypeMap: Record<string, LicenseOptions> = { abc: { ... } }
const siteIdMap: Record<number, SiteIdOptions> = { 12: { ... } }
type DynamicReferenceType =
| { type: 'LICENSE'; licenseName?: string; }
| { type: 'SITE_ID'; siteId?: number; };
export function getDynamicSchema(args: DynamicReferenceType) {
if (args.type === 'LICENSE') {
return licenseTypeMap[args.licenseName];
}
return siteIdMap[args.siteId];
}
const schema = getDynamicSchema({ type: 'license', licenseName: 'abc' })
// schema is of LicenseOptions | SiteIdOptions
【问题讨论】:
标签: typescript