menu
announcement

Spectrum is now read-only. Learn more about the decision in our official announcement.

TypeScript

A place to talk about TypeScript.

Channels
Team

Default values based on conditional types

November 16, 2020 at 12:05pm

Default values based on conditional types

November 16, 2020 at 12:05pm (Edited 1 year ago)
Hi to all! I was playing a bit with TS regarding conditional types and i was wondering if someone could clarify me a thing.
Schermata 2020-11-16 alle 12.54.27.png
Starting from this example, should the TS linter show me also the text property, since render is a string? And another question - in case the previous one is true - is there a way to set a default value based on the value of another prop? So in my case, is there a way to set the default value of text only in case render is a string?
Thanks to all

December 18, 2020 at 2:31pm
I have the same doubt

January 7, 2021 at 4:52pm
TypeScript can narrow the union in that way, if there is a discriminator of type literal on each of the elements in the union. (see https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#discriminating-unions and https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) Otherwise, each property will need to be checked, which is the behavior seen in the above example, where only the render property has been checked in the conditional, so it is displayed, other properties are unchecked, and therefore still unknown.
Edited
To simplify the existing code, without changing the MyProp type, consider using a type guard to narrow the type https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
Edited