Repository navigation
error TS2677: Type 'keyof E' is not assignable to type 'string' #23724
Copy link
Copy link
Closed
Labels
Breaking ChangeWould introduce errors in existing codeWould introduce errors in existing code
Description
Activity
This is a breaking change in TS 2.9 (documentation should come soon) introduced by #23592. With #23592
keyofnow returns all known keys of a types includingstring,numberandsymbolkeys. and as such, the constraint onkeyof Eis nowstring | number | symbol.If you are interested in getting only the string portions of the keys, use
Extract:function isKey<E>(str: string): str is Extract<keyof E, string> { return true; }
if your function is meant to handle all property names, including symbols, then consider widening the declaration of
str:function isKey<E> (str : string | number | symbol) : str is keyof E { return true; }
Reacted by AnyhowStep, Kagami Sascha Rosylight, Cristiano Santos, Arman Dezfuli-Arjomandi, Artem Malko, Dmitry, Christoph Lütjen, Viktor, Lihao Lin, Melchor Garau Madrigal and 50 moreReacted by netnichaa, Charlie Walter, Jonathan Tuzman, Renato Araujo Carneiro, Cethy and Jacob CoughenourReacted by Musa, Dan Minshew, Abhishek Datta, Yann RENAUDIN, Jorge Martins, netnichaa, Scott Bedard, Tate Thurston, Christian, banana and 5 moreReacted by netnichaa, Donghyun Lee, Tate Thurston, Charlie Walter, Renato Araujo Carneiro and Rémi Becheras- addedBreaking ChangeWould introduce errors in existing codeWould introduce errors in existing code
on Apr 26, 2018 Also, as a temporary measure you can use the new
--keyofStringsOnlycompiler option to revert to the old behavior.Reacted by AnyhowStep, Mitchell Lienau, Arman Dezfuli-Arjomandi, Artem Malko, chuan6, Thiago Delgado Pinto, Rubens Mariuzzo, polv, saostad, Joe Missamore and 4 moreReacted by saostad and Arthur KuzmnekoThanks for the swift response!
Reacted by Arman Dezfuli-Arjomandi- added a commit that references this issue
on Jun 25, 2018 - added a commit that references this issue
on Feb 22, 2019 - Reacted by Gustavo, Axel Bocciarelli, Richard Kemp, Avétis KAZARIAN, Stanley Stuart, S. Tarık Çetin, Shane Gardner, silentvow, Aria, AdrianDiazG and 8 more
For typescript 4, I use this in place of keyof as a current workaround to get accurate key types
type KeyTypes<T> = { [K in keyof T]-?: K extends string ? string : K extends number ? number : K extends symbol ? symbol : never }[keyof T]; type KeyOfType<T, KeyType extends string | number | symbol = KeyTypes<T>> = Extract<keyof T, KeyType>;
Reacted by Mike Pearson
Metadata
Metadata
Assignees
Labels
Breaking ChangeWould introduce errors in existing codeWould introduce errors in existing code

TypeScript Version: Version 2.9.0-dev.20180426
Search Terms: keyof not assignable string
Code
Expected behavior:
Should compile fine. The body of the type guard may actually correctly assert that
stris, indeed,keyof EWorks fine on TypeScript 2.8.3
Actual behavior:
Playground Link: Works on the playground
Related Issues: