how do i prevent non-nullable types in arguments #22375
Copy link
Copy link
Closed
Labels
QuestionAn issue which isn't directly actionable in codeAn issue which isn't directly actionable in code
Description
so we have the following convenience function:
export function asDefinedOr<T, D>(value: T | undefined, defaultValue: D): T | D {
return value !== undefined ? value : defaultValue;
}we would like to prevent the following from happening
declare var x : number;
asDefinedOr(x, 0); // <-- problem, unnecessary call, because x cannot be undefinedso we would like to make only T | undefined types allowed as aguments but not just T
is there a way to do it using conditional types?
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
QuestionAn issue which isn't directly actionable in codeAn issue which isn't directly actionable in code
Activity
jcalz commentedon Mar 7, 2018
This question should probably be on Stack Overflow or Gitter instead of here, if I understand the rules correctly.
But I can't stop myself because I love this sort of thing. Using conditional types:
zpdDG4gta8XKpMCd commentedon Mar 7, 2018
i asked about the
Notoperator #22323 (comment)which turned out being defined like this:
can my question be answered using it? something like:
jcalz commentedon Mar 7, 2018
No, that doesn't work. What's wrong with the code I wrote above?
zpdDG4gta8XKpMCd commentedon Mar 7, 2018
i don't like
anytherejcalz commentedon Mar 7, 2018
O....kay, then maybe
Note that
T extends anyandT extends topare not very different. Control flow analysis doesn't seem to know how to deal with conditional types the way I'd like, so I had to assert thatvaluewill beT extends undefined ? never : Tin the "then" branch of the ternary expression for it to type check.mhegazy commentedon Mar 7, 2018
+1 for Joe Calzaretta (@jcalz), not sure I would include the
voidpart though.jack-williams commentedon Mar 7, 2018
Interesting that you can constrain a type parameter based on itself! Cool solution Joe Calzaretta (@jcalz)
SalathielGenese commentedon Mar 8, 2018
I just feel like another reason to implemented type exclusion...
Now, coming to Joe Calzaretta (@jcalz) solution... I still don't understand how that constraint after function parameters work... It seem like the solution I've been looking for over two weeks now.
I purpose to sign a decorator
@Injectwith different signature depending whether it is applied on static or instance side :(cfg?: {type: SymbolConstructor | ConstructorLike})(cfg?: {id: string} | {type: SymbolConstructor | ConstructorLike} | {id: string, type: SymbolConstructor | ConstructorLike})The instance side allow specifying the
id. Here is how far I have gone :...and the use case bellow fail even where it is not expected :
Any help is welcome. Thanks.
typescript-bot commentedon Mar 23, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.