JohnWeisz / TypedJSON

Typed JSON parsing and serializing for TypeScript that preserves type information.
MIT License
603 stars 64 forks source link

Parsing array/set/map of primitive values #170

Closed rjkz808 closed 3 years ago

rjkz808 commented 3 years ago

Is it possible to deserialize collections of primitive values with typedjson without defining a schema? I mean something like this:

'[1, 2, 3, 4]' => number[]
'["a", "b", "c"]' => Set<string>
'{"a": 1, "b": 2, "c": 3}' => Map<string, number>
rjkz808 commented 3 years ago

P.S. I know that it's possible to do something like this:

const arr: String[] = TypedJSON.parseAsArray('["a", "b", "c"]', String);

But under the hood it'll use primitive value constructors (Number/String, etc.) instead of primitive values themself.

Neos3452 commented 3 years ago

Hi @rjkz808, why do you think it will use the constructors? By default, when TypedJSON sees a primitive it uses it directly (see deserializeDirectly function). The code below prints [ 'a', 'b', 'c' ], and true as expected.

        const result = TypedJSON.parseAsArray(
            '["a", "b", "c"]',
            String,
        );
        console.log(result);
        console.log(result[0] === 'a');