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

Redefine Object.keys to use keyof #20503

Closed
fathyb opened this issue Dec 6, 2017 · 3 comments
Closed

Redefine Object.keys to use keyof #20503

fathyb opened this issue Dec 6, 2017 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@fathyb
Copy link

fathyb commented Dec 6, 2017

TypeScript Version: 2.6.2

Code

interface MyIFace {
    key1: string
    key2: number
}
const MyObject: {[K in keyof MyIFace]: string} = {
    key1: 'foo',
    key2: 'bar'
}

declare function someFunction(key: keyof MyIFace): void

// error: Argument of type 'string' is not assignable to parameter of type '"key1" | "key2"'
Object.keys(MyObject).forEach(key => someFunction(key))

// error: Type 'string' is not assignable to type '"key1" | "key2"'
Object.keys(MyObject).forEach((key: keyof MyIFace) => someFunction(key))
Object.keys(MyObject).forEach((key: keyof typeof MyObject) => someFunction(key))

Expected behavior:

Object.keys(MyObject) should type it's return as (keyof typeof MyObject)[].

Actual behavior:

Object.keys(MyObject) types it's return as string[].

This can be easily fixed by defining Object.keys as follow :

declare const BetterObject: {
    keys<T extends {}>(object: T): (keyof T)[]
}

// OR

declare const BetterObject: {
    keys(object: {}): (keyof typeof object)[]
}

// everything works and key is infered as "key1" | "key2"
BetterObject.keys(MyObject).forEach(key => someFunction(key))
BetterObject.keys(MyObject).forEach((key: keyof MyIFace) => someFunction(key))
BetterObject.keys(MyObject).forEach((key: keyof typeof MyObject) => someFunction(key))
@aluanhaddad
Copy link
Contributor

This is intended see #12253 (comment)

@fathyb
Copy link
Author

fathyb commented Dec 6, 2017

@aluanhaddad I should've looked better, thanks

@fathyb fathyb closed this as completed Dec 6, 2017
@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 6, 2017
@RyanCavanaugh
Copy link
Member

image

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants