英文:
Correct way to return a property as a specific type from a union type
问题
我需要从应用程序中的不同位置的函数中返回一个属性。该属性可以是两种类型中的一种,都具有字符串文字属性。其中一种是另一种的扩展。如何在类型保护中将传入的同一变量强制转换为其中一种类型或另一种类型?
type NameA = 'A' | 'B' | 'C';
type NameB = NameA | 'D' | 'E';
function nameTypeGuard(
name: NameA | NameB
): NameA | NameB {
if (some condition) {
return name as NameA;
} else {
return name as NameB;
}
}
英文:
I have 1 property I need to return from a function in different places in an application.
This property could be 1 of 2 types, both have properties that are string literals. One is an extension of the other.
How can I return the same variable I am passing in cast as one type or the other in a type guard?
type NameA = 'A'| 'B' | 'C'
type NameB = NameA | 'D' | 'E'
function nameTypeGuard(
name: NameA | NameB
): NameA | NameB{
if (some condition) {
return name as NameA;
} else {
return name as NameB;
}
}
答案1
得分: 4
你可以使用条件类型作为返回类型。使用泛型,我的初始解决方案可能如下所示:
type NameA = 'A' | 'B' | 'C';
type NameB = 'A' | 'D' | 'E';
function nameTypeGuard<
T extends NameA | NameB,
R = T extends NameA ? NameA : NameB
>(
name: T
): R {
return name as unknown as R;
}
const a = nameTypeGuard("A");
const b = nameTypeGuard("B");
const c = nameTypeGuard("C");
const d = nameTypeGuard("D");
const e = nameTypeGuard("E");
TypeScript Playground: 链接
英文:
You can use a Conditional Type as the return type. Using Generics, my initial solution would look something like this:
type NameA = 'A' | 'B' | 'C';
type NameB = 'A' | 'D' | 'E';
function nameTypeGuard<
T extends NameA | NameB,
R = T extends NameA ? NameA : NameB
>(
name: T
): R {
return name as unknown as R;
}
const a = nameTypeGuard("A");
const b = nameTypeGuard("B");
const c = nameTypeGuard("C");
const d = nameTypeGuard("D");
const e = nameTypeGuard("E");
TypeScript Playground: Link
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论