typescript类型推断,如何根据object的一个key推断对象其他属性?

先上代码:

type DetailDataType = {
    detailType: 'type1'
    params: {
        a1: string
        test1: number
    }
} | {
    detailType: 'type2'
    params: {
        ss: Array<string>
        aa: Record<string, boolean>
    }
}

type dataType = { id: string } & DetailDataType

const testFn = <Type extends dataType['detailType']>(type: Type, data: unknown) => {
    if (type === 'type1') {
        const { a1, test1 } = data;
    }

    if (type === 'type2') {
        const { ss, aa } = data;
    }
};

testFn('type1', { a1: '', test1: 1 });
testFn('type1', { ss: [], aa: { test: false } });

问题:
该如何定义函数testFn的data参数,才能让data的解构与DetailDataType的定义相符,并且编辑器有提示,现在data的解构全是any,如下:
image.png
求ts大神解答,谢谢!!!

阅读 2.6k
2 个回答
type DetailDataType =
  | {
      detailType: "type1";
      params: {
        a1: string;
        test1: number;
      };
    }
  | {
      detailType: "type2";
      params: {
        ss: string[];
        aa: Record<string, boolean>;
      };
    };

type dataType = { id: string } & DetailDataType;

type Params<Type extends dataType["detailType"]> = Extract<
  dataType,
  { detailType: Type }
>["params"];

const testFn = <Type extends dataType["detailType"]>(
  type: Type,
  params: Params<Type>,
) => {
  if (type === "type1") {
    const { a1, test1 } = params as Params<"type1">;
  }
  if (type === "type2") {
    const { ss, aa } = params as Params<"type2">;
  }
};
testFn("type1", { a1: "", test1: 1 });
testFn("type2", { ss: [], aa: { test: false } });

别拆开,判断detailType的值来收窄类型

const testFn = (data: dataType) => {
  if (data.detailType === 'type1') {
      const { a1, test1 } = data.params;
  } else if (data.detailType === 'type2') {
      const { ss, aa } = data.params;
  }
};
推荐问题
logo
Microsoft
子站问答
访问
宣传栏