Reputation: 2587
type Test<T extends boolean = false> = {
a?: T;
};
const t: Test = {
a: true,
};
The code above complains about Type 'true' is not assignable to type 'false'.ts(2322)
Is there any way to achieve what I want?
=========== update ===========
Thanks for the comments and answers!
I thought when declaring a generic type, that T
is determined by the property that was given the T
.
So if I assign a: true
, that T
becomes true
; if I assign a: false
or undefined
, the T
uses the default false
.
Just like what function parameters and the defaults do.
So I have to explicitly tell ts Test<true>
?
What about this use case:
type RecursiveType<OK extends boolean = false> = { // 1
isOK: OK;
property: OK extends true ? ("a"|"b") : 0;
children?: Array<RecursiveType>; // 2
}
const recursive:RecursiveType = {
isOK: true;
property: 'a',
children: [
{
isOK: false,
property: 0
}
]
}
How to declare the type properly so my editor (vscode) give correct hints depends on isOK
?
Upvotes: 0
Views: 738
Reputation: 55152
If you don't pass any type to the generic it will use the default value, here false
.
You can either do
const t: Test = { // no type === will only accept false
a: false,
};
or
const t: Test<true> = { // will only accept the type passed to the generic
a: true,
};
Upvotes: 2