【问题标题】:How do I declare a type where I pick a property from an Interface and make the picked property's properties optional?如何声明从接口中选择属性的类型并使选择的属性的属性可选?
【发布时间】:2019-12-22 11:49:48
【问题描述】:

就像在这个例子中一样,我不想选择一个属性并使整个事情成为可选的。但相反,我想将选择的属性设为可选。

目前我正在通过显式写{items: Partial<Item>[]}来解决这个问题。

有没有更聪明的方法?


interface Item{
    id: number
    name: string
}

interface User{
    id: number
    name: string

    items: Item[]
}

type UserWithOptionalItemsItself = Pick<User, "id" | "name"> & Partial<Pick<User, "items">>
const x:UserWithOptionalItemsItself = {
    id: 1,
    name: "user name",
    // items is optional.. this is not what I want
}

type UserWithOptionalItems = Pick<User, "id" | "name"> & {items: Partial<Item>[]}
const y:UserWithOptionalItems = {
    id: 1,
    name: "user name",
    // you have to have items, but the properties are optional
    items: [{
        id: 123
    }]
}

TypeScript playground example

【问题讨论】:

    标签: typescript typescript2.0 typescript-generics


    【解决方案1】:

    这里,idname 是必需的,而 items 是可选的。如果未提供,他们将返回undefined

    您还可以为项目提供默认值:

    interface User{
        id: number
        name: string
    
        items?: Item[] | undefined
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多