Default values based on conditional typesNovember 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.
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
textonly in case
renderis a string?
Thanks to all
December 18, 2020 at 2:31pm
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
renderproperty has been checked in the conditional, so it is displayed, other properties are unchecked, and therefore still unknown.
To simplify the existing code, without changing the
MyProptype, consider using a type guard to narrow the type https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards