es6使用打字稿的函数解构参数

我仍然想使用解构,因为在视觉上它有助于调用函数。但是我在函数参数中这样做有一个问题:

const t = ({id, name}: {number, string}) => `id: ${id} name:${name}`

另一种失败的方法,我尝试避免将所有类型的参数放在一行中,而是使用一个接口:

interface tParams {
    id: number,
    name: string
}
const t = ({id, name} as tParams) => `id: ${id} name:${name}`

Playground Link

评论
  • wet
    wet 回复

    You need not use as for typing while using destructuring. You can instead write it as follows

    interface tParams {
        id: number,
        name: string
    }
    const t2 = ({id, name}: tParams) => `id: ${id} name:${name}`
    
  • Lily
    Lily 回复

    您可以这样做:

    const t = ({id, name}: {id: number, name: string}) => `id: ${id} name:${name}`
    

    或者这样:

    interface tParams {
        id: number,
        name: string
    }
    const t = ({id, name}: tParams) => `id: ${id} name:${name}`