Ts-toolbelt: ValidPath without const assertion?

Created on 16 Jun 2020  路  6Comments  路  Source: millsp/ts-toolbelt

馃 Question

I'm new to this library, and am still trying to get my head around it. It's very impressive! :)

In this sample https://pirix-gh.github.io/ts-toolbelt/modules/_object_pathvalid_.html there's the following code:

const test0 = getAt(state,          ['case', 'name'] as const) // {c: number}

Why is const needed? And is there a way to make it work without the const assertion?

Hope you can help.

question

Most helpful comment

I posted a solution to this problem here in https://github.com/microsoft/TypeScript/issues/30680. It will land soon in ts-toolbelt.

All 6 comments

Hi there,

Without a const assertion, the type of ['case', 'name'] would be narrowed to string[] that's all. Depending on your type safety needs, you would choose as const or not.

I somehow missed your answer, sorry! What I meant was that, I'd like the type safety to be enforced by the function signature, so the caller does not have to add as const, but still only be able to pass expected strings in the array. It's easy for a caller to forget as const and thus we will not catch errors now or when the allowed string values change in the future.

It's a TypeScript limitation, I know how inconvenient this is. To work around that, the only solution is to take rest parameters instead. Or you could have this Maybe this can help you:

Thanks a lot for your swift reply :)

I'll look into those links right away!

I posted a solution to this problem here in https://github.com/microsoft/TypeScript/issues/30680. It will land soon in ts-toolbelt.

This is amazing, thank you for doing this! I look forward to it landing is ts-toolbelt too.

Was this page helpful?
0 / 5 - 0 ratings