如何在函数typescript函数中提取和推断类型参数



我有以下代码:

type Input = { type: 'a'; data: 'x' | 'y' } | { type: 'b'; data: 'y' | 'z' }
type DataType<T extends Input['type']> = Extract<Input, { type: T }>['data']
export const f = <T extends Input['type']>(
type: T,
data: DataType<T>
): Input => ({ type, data })

如果在typescript中出现类似

的代码将会失败
Type '{ type: "a" | "b"; data: "x" | "y" | "z"; }' is not assignable to type 'Input'.
Type '{ type: "a" | "b"; data: "x" | "y" | "z"; }' is not assignable to type '{ type: "b"; data: "y" | "z"; }'.
Types of property 'type' are incompatible.
Type '"a" | "b"' is not assignable to type '"b"'.
Type '"a"' is not assignable to type '"b"'

关于如何锁定type以使其工作有任何想法吗?

走远一点的路可以解决你的问题。

interface InputTypeMapping {
a: 'x' | 'y';
b: 'y' | 'z';
}
type Input = { type: keyof InputTypeMapping, data: InputTypeMapping[keyof InputTypeMapping] };
type DataType<T extends keyof InputTypeMapping> = InputTypeMapping[T];
export const f = <T extends keyof InputTypeMapping>(
type: T,
data: DataType<T>
): Input => ({ type, data });

最新更新