You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Item 35: Prefer More Precise Alternatives to String Types
Things to Remember
Avoid "stringly typed" code. Prefer more appropriate types where not every string is a possibility.
Prefer a union of string literal types to string if that more accurately describes the domain of a variable. You'll get stricter type checking and improve the development experience.
Prefer keyof T to string for function parameters that are expected to be properties of an object.
Code Samples
interfaceAlbum{artist: string;title: string;releaseDate: string;// YYYY-MM-DDrecordingType: string;// E.g., "live" or "studio"}
constkindOfBlue: Album={artist: 'Miles Davis',title: 'Kind of Blue',releaseDate: newDate('1959-08-17'),recordingType: 'Studio'// ~~~~~~~~~~~~ Type '"Studio"' is not assignable to type 'RecordingType'};
functionpluck<T>(records: T[],key: string): any[]{returnrecords.map(r=>r[key]);// ~~~~~~ Element implicitly has an 'any' type// because type '{}' has no index signature}