Tom Le
Tom Le

Reputation: 127

How can I remove properties without using option(?) in typescript

I have problems about removing properties. For example:

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,
})

In this case first doesn't need getName property. How can I solve that.


Using optional '?' property it will cause unclearly output. For example

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

How can I make clearly output? Thanks for reading.

Upvotes: 0

Views: 39

Answers (1)

artem
artem

Reputation: 51719

So you want first type to be inferred as {}, and second type as { getName: (name: string) => string; } ?

Here is one way to do that:

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,
})

Upvotes: 2

Related Questions