首页 > 解决方案 > 如何在打字稿中不使用选项(?)删除属性

问题描述

我有关于删除属性的问题。例如:

type Person<GN>  = {
    getName: GN extends never ? never :  GN,
}

const foo =  <GN>(person: Person<GN>) => person

const first = foo({}) // should work

const second = foo({
    getName: (name: string) => name,
})

在这种情况下,首先不需要 getName 属性。我该如何解决。


使用可选的“?” 属性会导致输出不清晰。例如

type Person<GN>  = {
    getName?: GN,
}

const foo =  <GN>(person: Person<GN>) => person

const first = foo({}) // should work
first.getName // shouldn't exist 'getName' => but still have

const second = foo({
    getName: (name: string) => name,
})

second.getName // should exist getName but in this case is optional property

我怎样才能清楚地输出?谢谢阅读。

标签: typescript

解决方案


因此,您希望firsttype 被推断为{},并且secondtype 为{ getName: (name: string) => string; }?

这是一种方法:

type Person<GN> = { getName: GN }

const foo = <GN, P extends Partial<Person<GN>>>(person: P) => person;

const first = foo({}) // const first: {}

const second = foo({  // const second: { getName: (name: string) => string; }
    getName: (name: string) => name,
})

推荐阅读