LongTengDao / j-toml

A Node.js implementation of TOML written by LongTengDao. Belong to "Plan J"./龙腾道为汤小明语写的 Node.js 实现。从属于“简计划”。
https://npmjs.com/package/@ltd/j-toml
GNU Lesser General Public License v3.0
55 stars 6 forks source link

How can I define custom typescript type for parsed data? #12

Closed danechitoaie closed 3 years ago

danechitoaie commented 3 years ago

I'm trying to use the following code:

TOML.parse<{ a: string; b: string }>(tomlSource, {
    joiner: "\n",
    bigint: false,
});

but this give the following error:

Argument of type '{ joiner: string; bigint: false; }' is not assignable to parameter of type '{ joiner?: string | undefined; bigint?: number | boolean | undefined; x: TagProcessor<{ a: string; b: string; }> | ({ readonly tag: TagProcessor<{ a: string; b: string; }>; readonly null?: boolean | undefined; } & TypeAgnosticOptions); }'. Property 'x' is missing in type '{ joiner: string; bigint: false; }' but required in type '{ joiner?: string | undefined; bigint?: number | boolean | undefined; x: TagProcessor<{ a: string; b: string; }> | ({ readonly tag: TagProcessor<{ a: string; b: string; }>; readonly null?: boolean | undefined; } & TypeAgnosticOptions); }'.ts(2345) index.d.ts(25, 194): 'x' is declared here.

So it asks me to define x: TagProcessor<{ a: string; b: string; }>. What is this?

Thanks.

LongTengDao commented 3 years ago

TOML.parse does not support argumentType, please use as (which is the actual behaviour for a parser program -- it does not know the source, and can not help you to make type checking):

TOML.parse(tomlSource, {
    joiner: "\n",
    bigint: false,
}) as { a :string, b :string };

If you need a real type check, you may need an asserts function:

const root = TOML.parse(tomlSource, {
    joiner: "\n",
    bigint: false,
});

function assertsABString (value :{ [name :string] :unknown }) :asserts value is { a :string, b :string } {
    if ( typeof value.a!=='string' ) { throw TypeError('...'); }
    if ( typeof value.b!=='string' ) { throw TypeError('...'); }
}
assertsABString(root);