是否可以解构和键入具有已知属性的函数参数对象?

Is it possible to destructure and type a function param object with known properties?

Typescript playground

用例:获取具有已知属性的单个对象的函数。需要同时解构和赋值

这个有效:

type OBJECT_PARAM = {
  pathname: string,
  routePath: string
}

export const getSlugMatch = (props: OBJECT_PARAM)
: string => {
    const { pathname, routePath } = props;
    return "SOME_SLUG"
};

这个工作:

export const getSlugMatch_V2 = ({pathname: string, routePath: string}): string => {
    return "SOME_SLUG"
};

有什么办法解决这个问题吗?人们通常如何处理这种情况?我真的需要定义 OBJECT_PARAM 吗?

我猜它不起作用,因为它与重命名解构属性的 Javascript 方式冲突。最好的解决方法是什么?

解构需要与类型分开,因为正如您所说,属性 冒号语法已用于重命名。你能做的最好的事情就是声明内联类型:

export const getSlugMatch_V2 = ({pathname, routePath}: {pathname: string, routePath: string}): string => {
    return "SOME_SLUG"
};