Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect return type when a union type is used by a partial get function #20957

Closed
sebinsua opened this issue Oct 24, 2017 · 0 comments
Closed

Comments

@sebinsua
Copy link
Contributor

sebinsua commented Oct 24, 2017

Closed as this was the wrong repository... See: microsoft/TypeScript#14400 (comment)


In situations in which I wish to use a partial get function TypeScript doesn't seem able to work out the return type correctly.

TypeScript 2.5.3

interface Props {
    property: boolean;
    someProperty: string;
    someOtherProperty: number;
}

const obj = {
    property: true,
    someProperty: 'some property',
    someOtherProperty: 9999
}

function get1<T, K extends keyof T = keyof T>(k: K) {
    return (obj: T): T[K] => obj[k]
}

function get2<T, K extends keyof T = keyof T>(k: K, obj: T): T[K] {
    return obj[k]
}

// Why do I need to supply 'someProperty' as the second type argument to get this to work?
const getSomeProperty = get1<Props>('someProperty')
const someProperty = getSomeProperty(obj) // Type is `string | number | boolean`

// The type is worked out correctly here.
const someProperty2 = get2('someProperty', obj); // Type is `string`

Other than calling get1<Props, 'someProperty'>('someProperty') what could I do to dynamically create a getSomeProperty function which returns a string?

// Perhaps it was wrong for me to set a default type for K, but if I remove it completely then
// on usage of `get1` I get an error message: "Expected 2 type arguments, but got 1" which
// as far as I can tell, still has the same problem and forces the same inelegant approach.

function get1<T, K extends keyof T>(k: K) {
    return (obj: T): T[K] => obj[k]
}

Sorry, if this isn't the right place for this. I use this style of coding quite frequently in libraries that I write, and I want to find out whether this feature request is being tracked somewhere so I can follow it. Or if there is already some elegant syntax to do this, I want to know what it is!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant