2

I have a method like this.

private getStuff(data: string[]) : CertainType[] { ... }

I decided that it makes more sense to have the output in form of a dictionary (C#'ish) than an array. As far my google-foo tells me, I should use an object and put in stuff into it with the ID as the fields' names. So instead of:

const things: Thing[]; ...
things = [];
output.push(thingy);
console.log(things[3]);

I'm doing this:

const stuff: any; ...
stuff = { };
stuff[3] = stuffy;
console.log(things[3]);

So the signature of the method changed to this.

private getStuff(data: string[]) : any { ... }

It all works just dandy but. I like the semi-hard typed variables in TypeScript and coming from C# I strongly believe in avoiding a lot of issues by being (seemingly) nit-picky in advance (without getting within range of PO. of course).

Since the number of properties isn't known in advance, nor are their IDs, I wonder if any is the closest type setting or if there's something corresponding to the syntax of C# as:

Dictionary<string, Thing> dicky;

1 Answer 1

2

If you need an object that can be indexed by any string but all values in the object are of a certain type you need a type with an index signature.

This can be written as

const stuff: Record<string, Thingy> = {};

Or, more verbosely, but equivalent:

const stuff: { [index: string]: Thingy } = {};
Sign up to request clarification or add additional context in comments.

5 Comments

Like they say in Amazing Grace: "Oh, I was blind but now I C#"... Perfect! I'm going refactor me some code right away.
@KonradViltersten glad to hear, don't forget to upvote and mark as answered :)
Don't be so quick with the reply, then. I was hitting "accept" but it told me to wait for 59 seconds. You are simply too helpful. :)
Right, as we're waiting for the time block to accept - in the first sample you're assuming that I have a class called Record, right? If I don't have a specialized class for it, I have to use the verbose, syntax. Is that correctly understood?
@KonradViltersten no, Record is predefined, you can use it. They are the same thing essentially Record<string, Thingy> == { [index: string]: Thingy }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.