TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

'type' aliases of string can not be used as object index signature.

Open jlennox opened this issue 11 years ago • 60 comments

type Guid = string;
var foo: { [deviceId: Guid]: DateTime } = {};

Generates the error:

An index signature parameter type must be 'string' or 'number'.

It would be nice to be able to type indexes using string-aliases.

jlennox avatar Jan 23 '15 01:01 jlennox

+1

aelr avatar Feb 16 '15 06:02 aelr

This includes the alias String.

class Map<T> {
    [key: String]: T
}

MicahZoltu avatar Jul 05 '15 00:07 MicahZoltu

It would seem you also can't pass aliased types to an indexer either:

class Map<T> {
    [key: string]: T
}

let map: Map<number> = ...
let key: String = ...
let value = map[key]; // error

An index expression argument must be of type 'string', 'number', 'symbol, or 'any'

And yes, there is a missing ' in the error message.

MicahZoltu avatar Jul 05 '15 00:07 MicahZoltu

String is not an alias for string. It refers to the non-primitive type String in JavaScript.

RyanCavanaugh avatar Jul 06 '15 16:07 RyanCavanaugh

Ah I didn't know that, thanks! I suppose this means I should be using string, number and boolean (lowercase) everywhere in my code rather than String, Number and Boolean. Most unfortunate.

MicahZoltu avatar Jul 06 '15 17:07 MicahZoltu

what is the point in aliasing string?

zpdDG4gta8XKpMCd avatar Jan 04 '16 23:01 zpdDG4gta8XKpMCd

aleksey's question is probably the most relevant.

This falls under the category of not appearing to do something you don't. Specifically, all type aliases of a type are equivalent, so you could still index foo by a CustomerName.

There's already a place to write the intended index semantics (deviceId should probably be deviceGuid ?). Adding a second place to write that same information doesn't help because it makes it look like the compiler will enforce the specific indexing type, when in reality it won't.

One nascent proposal at the moment is "Fresh types" which would allow an enforcement of the indexing type. If that ends up happening, we'd definitely revisit this.

RyanCavanaugh avatar Jan 05 '16 00:01 RyanCavanaugh

didn't mean to play a devil's advocate, aliasing a string might be helpful at early prototyping stages where, say, ID isn't yet clear to be a string or a number, using an alias to either can reduce refactoring effort, but this use case is too dubious to get enough justification

if people think that aliasing would create a new type incompatible with the original one, so they can benefit from such distinction, it's a dangerous fallacy and illusion (need nominate types to do so) On Jan 4, 2016 7:01 PM, "Ryan Cavanaugh" [email protected] wrote:

aleksey's question is probably the most relevant.

This falls under the category of not appearing to do something you don't. Specifically, all type aliases of a type are equivalent, so you could still index foo by a CustomerName.

There's already a place to write the intended index semantics (deviceId should probably be deviceGuid ?). Adding a second place doesn't help because it makes it look like the compiler will enforce the specific indexing type when it won't.

One nascent proposal at the moment is "Fresh types" which would allow an enforcement of the indexing type. If that ends up happening, we'd definitely revisit this.

— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/1778#issuecomment-168849193 .

zpdDG4gta8XKpMCd avatar Jan 05 '16 00:01 zpdDG4gta8XKpMCd

One nascent proposal at the moment is "Fresh types" which would allow an enforcement of the indexing type. If that ends up happening, we'd definitely revisit this.

That would indeed be more inline with what I'm after. Thank you for the update.

jlennox avatar Jan 05 '16 17:01 jlennox

I use aliases to the string type to differentiate between different string types. I know they aren't compile time enforced, but they act as useful documentation. Not being able to use them as object keys seems quite arbitrary and not in line with what a type alias is. Should I not be able to use an alias anywhere I could use the aliased type? If that is the design intent, I'd love to know what those situations are and why they were chosen. Thanks.

Yona-Appletree avatar May 04 '16 18:05 Yona-Appletree

Until a better solution is available, one alternative is to use JSDocs:

type Guid = string;
/** @type {Object.<Guid, DateTime>} */
var foo: { [deviceId: string]: DateTime } = {};

This will at least favor your future greps and offer a hint in your JSDocs / VSCode definition popups. You could also use the following syntax but I believe it only happens to work and is incorrect:

type Guid = string;
var foo: { [deviceId in Guid]: DateTime } = {};
foo.bar = new DateTime();

niedzielski avatar Apr 21 '18 21:04 niedzielski

There is a work-around we're thinking about using to get type-enforcement of different categories of strings (e.g. ids for different types of objects), and to track those properly through being used as object keys, which is to declare them (inaccurately) as string literals, since those are the only types that can be used productively as index types in an object.

 //nothing actually takes these runtime values, but they allow the type system to reason about categories of strings (including unions of id types)
type StudentId = 'any_student_id_value'
type ClassId = 'any_class_id_value'

to create them, you just need to cast a string (either directly, or wrapped in a constructor-like function:

const studentId = 'abc' as StudentId
const classId = 'abc' as ClassId

The type system behavior is quite sane for this use case, and you can do things like:

const studentToClass:{[id:StudentId]?:ClassId}

and get type safety against accidental switches for both reads and writes for keys and values, including fairly readable error messages (checking is the best with noImplicitAny enabled).

And they can also be used directly as strings, so it has no impact on interpolation, serialization, etc.

I'd be very interested in knowing if anyone else has tried this approach and knows if this is a sane path, or if there is some reason this will be a bad idea (Other than the obvious, that this isn't safe against use of constant strings which happen to match the specific strings, which we've decided is less of a problem than the problem this is solving).

ehberger avatar Jul 03 '18 16:07 ehberger

I sometimes use aliases the same way as @Yona-Appletree does. When I work with Ethereum's addresses I create alias export type Address = string. I understand @aleksey-bykov's point, but why should the case of object's index differ from using an alias in for example function's parameter? e.g (myParam: Address) => myParam is completely fine. I don't see the point of explicitly forbidding of using aliases in object's index.

Could we mb reopen this issue, please?

ondratra avatar Oct 23 '18 09:10 ondratra

Agreed.. PLEASE open this up... every time I have a custom string format (ISO8601 dates, email addresses, etc) I prefer to use a type alias rather than a raw "string"...

this is important to have!

InputNeuron avatar Dec 29 '18 17:12 InputNeuron

Using type aliases over raw primitive types is useful especially in big systems with heavy domain logic.

Example usecase: a bookkeeping system or e-commerce system. First you start with a local currency with number. But after the system grows big and have lots of customers and you need to replace number with { amount: number, currency: Currency } in few hundred places, then good luck. Instead, you start with type Money = number, use Money everywhere. And when you need to change the entity, you'll get precise list of all places where compiler finds an error, the ones that you need to update (with primitive number you would get errors as well, but not in the places you need to update, less convenient).

It's basically a Value Object in DDD. TS Aliases are superb with it.

ducin avatar Jan 05 '19 15:01 ducin

@ducin That's an excellent point!

ondratra avatar Jan 06 '19 14:01 ondratra

@ducin there is a better idea to that called units of measure, with a couple of implementations (near the bottom): https://github.com/Microsoft/TypeScript/issues/364

zpdDG4gta8XKpMCd avatar Jan 06 '19 14:01 zpdDG4gta8XKpMCd

@aleksey-bykov why "better" if DDD is a well-established and commonly used approach?

ducin avatar Jan 06 '19 14:01 ducin

because if we follow your example it lets you differentiate Money further by assigning a unit of measure to them (think dollars or euro) making them inmediately incompatible YET convertable to one another using just the arithmetic

zpdDG4gta8XKpMCd avatar Jan 06 '19 14:01 zpdDG4gta8XKpMCd

Not sure if I understand your point. I don't want to recalculate anything. I want to extend (==update) my model all along my codebase. I don't want to keep the old model. And I want TS to show me all the places I need to update. But let me give another examples...


Extending a number into number X currency is only one example. You might have lots of examples that do not fall into "units of measures" which is more narrow (comparing to Value Objects).

Example: how do you define identity (of a user, of a tenant, whatever). It can be a number (id), a guid (string) or a whole combination. Can't see how you apply "units of measures" into identity (you don't recalculate anything here).

Example: you've got a HR system where employees / candidates have Skills. Skill is something meaningful in your app, lets you search, aggregate data, analyse, etc. You can start with a string, type Skill = string and then use Skill throughout your codebase. Then, if you need it, you extend a Skill to be { Skill: string, level: string }. And you want to have more convenient refactors.

And, basically, type aliases would be useful to be used within index signatures in this strategy (when you want to have a VO as an index). Also, using type aliases throughout your codebase increases readability. I'd prefer to have Skill type where skills apply instead of string.


PS Value Objects in DDD are not meant to calculate stuff. First and foremost they allow you to check for equality (if a JS skill is the the same as JavaScript skill, for example). They are plain structures + equality bool fn.

ducin avatar Jan 06 '19 14:01 ducin