Typescript return 基于对象值的类型 属性
Typescript return type based on value of object property
我有以下代码,它有点基于 到一个类似的问题:
interface A {
type: "a";
data: string;
}
interface B {
type: "b";
data: string;
}
type Helper<T extends A | B> =
T["type"] extends A["type"] ? A :
T["type"] extends B["type"] ? B :
never;
const get = <T extends A | B>({ type }: Pick<T, "type">): Helper<T> => {
return {
type,
data: type,
} as Helper<T>;
};
const mySelected = get({ type: "a" });
console.log(mySelected);
我的get
函数应该return一个A
类型的对象,如果第一个参数类型是a
,如果第一个参数是B
类型的对象参数类型是“b”。
然而在我的代码中 mySelected
的类型是 never.
如果我将函数调用更改为 get<A>({ type: "a" })
,我会得到正确的 A
类型,但我希望 Typescript 自己解决这个问题。此外,如果我将函数调用更改为 get<B>({ type: "a" })
,Typescript 会注意到有问题并抱怨 Type '"a"' is not assignable to type '"b"'.
.
基于您链接的:
interface A {
type: "a";
data: string;
}
interface B {
type: "b";
data: string;
}
const get = <T extends Pick<A | B, 'type'>>({ type }: T ) => {
return {
type,
data: type,
} as T extends Pick<A, 'type'> ? A :
T extends Pick<B, 'type'> ? B :
never
};
const mySelectedA = get({ type: "a" }); // const mySelectedA: A
const mySelectedB = get({ type: "b" }); // const mySelectedB: B
const mySelectedC = get({ type: "c" }); // const mySelectedC: never | Type '"c"' is not assignable to type '"a" | "b"'.(2322)
我有以下代码,它有点基于
interface A {
type: "a";
data: string;
}
interface B {
type: "b";
data: string;
}
type Helper<T extends A | B> =
T["type"] extends A["type"] ? A :
T["type"] extends B["type"] ? B :
never;
const get = <T extends A | B>({ type }: Pick<T, "type">): Helper<T> => {
return {
type,
data: type,
} as Helper<T>;
};
const mySelected = get({ type: "a" });
console.log(mySelected);
我的get
函数应该return一个A
类型的对象,如果第一个参数类型是a
,如果第一个参数是B
类型的对象参数类型是“b”。
然而在我的代码中 mySelected
的类型是 never.
如果我将函数调用更改为 get<A>({ type: "a" })
,我会得到正确的 A
类型,但我希望 Typescript 自己解决这个问题。此外,如果我将函数调用更改为 get<B>({ type: "a" })
,Typescript 会注意到有问题并抱怨 Type '"a"' is not assignable to type '"b"'.
.
基于您链接的
interface A {
type: "a";
data: string;
}
interface B {
type: "b";
data: string;
}
const get = <T extends Pick<A | B, 'type'>>({ type }: T ) => {
return {
type,
data: type,
} as T extends Pick<A, 'type'> ? A :
T extends Pick<B, 'type'> ? B :
never
};
const mySelectedA = get({ type: "a" }); // const mySelectedA: A
const mySelectedB = get({ type: "b" }); // const mySelectedB: B
const mySelectedC = get({ type: "c" }); // const mySelectedC: never | Type '"c"' is not assignable to type '"a" | "b"'.(2322)