Neo
Neo

Reputation: 4760

Typescript Pick issues

My simplified code block is like the following

interface A {
    val: string;
    // Other optional parameters
}

function usingObject(obj: A) {
    return obj.val
}

function usingVal(val: Pick<A, 'val'>) {
    return usingObject({ val })
}

i am getting the following error

Type 'Pick<A, "val">' is not assignable to type 'string'.ts(2322)

I want a function which can accept object and other function which take each mandatory parameter as an argument

Upvotes: 4

Views: 2066

Answers (3)

Jamen
Jamen

Reputation: 199

This is because Pick is returning us { key: type } but not just the type. In this case

interface A {
    val: string;
}

Pick<A, 'val'>
// returns -> { val: string }
// but not -> string

So you are going to do

function usingVal({ val }: Pick<A, 'val'>) {
    return usingObject({ val })
}

or

function usingVal(val: Pick<A, 'val'>) {
    return usingObject({ val: val.val })
}

Upvotes: 4

WSD
WSD

Reputation: 3587

Probably we should know more about your usingObject implementation, but the following worked for me:

function usingVal(val: Pick<A, 'val'>) {
  return usingObject(val)
}

Upvotes: 2

fresskoma
fresskoma

Reputation: 25781

The result type of Pick<A, 'val'> is essentially the same as interface A. In other words, Pick<...> constructs a new object type.

It appears that the following would work for you:

function usingVal(val: string) {
    return usingObject({ val })
}

Upvotes: 2

Related Questions