-
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathnullishCoalescing.spec.ts
More file actions
75 lines (66 loc) · 2.43 KB
/
nullishCoalescing.spec.ts
File metadata and controls
75 lines (66 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import * as util from "../util";
test.each(["null", "undefined"])("nullish-coalesing operator returns rhs", nullishValue => {
util.testExpression`${nullishValue} ?? "Hello, World!"`
.ignoreDiagnostics([2871 /* TS2871: This expression is always nullish. */])
.expectToMatchJsResult();
});
test.each([3, "foo", {}, [], true, false])("nullish-coalesing operator returns lhs", value => {
util.testExpression`${util.formatCode(value)} ?? "Hello, World!"`
.ignoreDiagnostics([
2869 /* TS2869: Right operand of ?? is unreachable because the left operand is never nullish. */,
])
.expectToMatchJsResult();
});
test.each(["any", "unknown"])("nullish-coalesing operator with any/unknown type", type => {
util.testFunction`
const unknownType = false as ${type};
return unknownType ?? "This should not be returned!";
`
.ignoreDiagnostics([2871 /* TS2871: This expression is always nullish. */])
.expectToMatchJsResult();
});
test.each(["boolean | string", "number | false", "undefined | true"])(
"nullish-coalesing operator with union type",
unionType => {
util.testFunction`
const unknownType = false as ${unionType};
return unknownType ?? "This should not be returned!";
`.expectToMatchJsResult();
}
);
test("nullish-coalescing operator with side effect lhs", () => {
util.testFunction`
let i = 0;
const incI = () => ++i;
return [i, incI() ?? 3, i];
`.expectToMatchJsResult();
});
test("nullish-coalescing operator with side effect rhs", () => {
util.testFunction`
let i = 0;
const incI = () => ++i;
return [i, undefined ?? incI(), i];
`
.ignoreDiagnostics([2871 /* TS2871: This expression is always nullish. */])
.expectToMatchJsResult();
});
test("nullish-coalescing operator with vararg", () => {
util.testFunction`
function foo(...args: any[]){
return args
}
function bar(...args: any[]) {
let x: boolean | undefined = false
const y = x ?? foo(...args)
}
return bar(1, 2)
`.expectToMatchJsResult();
});
test.each([true, false, null])("nullish-coalescing with generic lhs (%p)", lhs => {
util.testFunction`
function coalesce<A, B>(a: A, b: B) {
return a ?? b
}
return coalesce(${lhs}, "wasNull")
`.expectToMatchJsResult();
});