Skip to content

Type inference not works inside function while works well on params #32436

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

Closed
k8w opened this issue Jul 17, 2019 · 4 comments
Closed

Type inference not works inside function while works well on params #32436

k8w opened this issue Jul 17, 2019 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@k8w
Copy link

k8w commented Jul 17, 2019

TypeScript Version: 3.5.3

Search Terms: Type inference function

Code

interface ValueType {
    a: { a: string };
    b: { b: string };
    c: { c: string };
}

function setValue<T extends keyof ValueType>(key: T, value: ValueType[T]) {
    if (key === 'a') {
        console.log(value.a);
    }
}

Expected behavior:
Compile succ

Actual behavior:
test.ts:9:27 - error TS2339: Property 'a' does not exist on type 'ValueType[T]'.
9 console.log(value.a);

Playground Link:

Related Issues:
#31904

@Succubussix
Copy link

Succubussix commented Jul 17, 2019

interface ValueType {
    a: { a: string };
    b: { b: string };
    c: { c: string };
}

function setProperty<T, K extends keyof T>(obj: T, key: K, value: ValueType) {
    // obj[key] = value;
    if (key === 'a') {
        console.log(value.);
    }
}

i think this is what you are trying to do ?

image

nvm

@jack-williams
Copy link
Collaborator

Duplicate of #13995.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jul 23, 2019
@RyanCavanaugh
Copy link
Member

This is a correct error. A legal call to this function is

setValue<"a" | "b">("a", { b: "" } );

@k8w
Copy link
Author

k8w commented Jul 24, 2019

@RyanCavanaugh @Dj-jom2x
setValue("a", { b: "" }); is not a legal call.

It would get error as expect

error TS2345: Argument of type '{ b: string; }' is not assignable to parameter of type '{ a: string; }'.
Object literal may only specify known properties, and 'b' does not exist in type '{ a: string; }'.

What I try to achieve is to let key and value match.

The issue is:

  1. Type inference works well on function call params checking
  2. But it do not works inside the function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants