File size: 12,038 Bytes
d0faac4 | 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | You are working in `/workspace/typescript`, a source tree checked out at
the base commit for this task. Implement the requested behavior in the source
tree, then run:
```bash
lolbench-submit
```
Do not stop after editing files, running tests, or describing the solution. The
task is complete only when `lolbench-submit` has created
`/logs/artifacts/solution.patch`. If that file does not exist, continue
working and run `lolbench-submit` again.
That command writes your implementation diff to
`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifier
will grade. Before running `lolbench-submit`, clean or revert any test files
you created or modified; test files must not be included in the final
`solution.patch`.
This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.
Now please implement the following requirements in the source tree:
---
# "satisfies" operator to ensure an expression matches some type (feedback reset)
# Feature Update - February 2022
This is a feedback reset for #7481 to get a fresh start and clarify where we are with this feature. I really thought this was going to be simpler, but it's turned out to be a bit of a rat's nest!
Let's start with what kind of scenarios we think need to be addressed.
## Scenario Candidates
First, here's a review of scenarios I've collected from reading the linked issue and its many duplicates. **Please post if you have other scenarios that seem relevant**. I'll go into it later, but *not all these scenarios can be satisfied at once* for reasons that will hopefully become obvious.
### Safe Upcast
Frequently in places where control flow analysis hits some limitation (hi #9998), it's desirable to "undo" the specificity of an initializer. A good example would be
```ts
let a = false;
upd();
if (a === true) {
// ^^^ error, true and false have no overlap
// ...
}
function upd() {
if (someCondition) a = true;
}
```
The canonical recommendation is to type-assert the initializer:
```ts
let a = false as boolean;
```
but there's limited type safety here since you could accidently downcast without realizing it:
```ts
type Animal = { kind: "cat", meows: true } | { kind: "dog", barks: true };
let p = { kind: "cat" } as Animal; // Missing meows!
upd();
if (p.kind === "dog") {
} else {
p.meows; // Reported 'true', actually 'undefined'
}
function upd() {
if (Math.random() > 0.5) p = { kind: "dog", barks: true };
}
```
The safest workaround is to have a dummy function, `function up<T>(arg: T): T`:
```ts
let a = up<boolean>(true);
```
which is unfortunate due to having unnecessary runtime impact.
Instead, we would presumably write
```ts
let p = { kind: "cat", meows: true } satisfies Animal;
```
### Property Name Constraining
We might want to make a lookup table where the property keys must come from some predefined subset, but not lose type information about what each property's value was:
```ts
type Keys = 'a' | 'b' | 'c' | 'd';
const p = {
a: 0,
b: "hello",
x: 8 // Should error, 'x' isn't in 'Keys'
};
// Should be OK -- retain info that a is number and b is string
let a = p.a.toFixed();
let b = p.b.substr(1);
// Should error even though 'd' is in 'Keys'
let d = p.d;
```
There is no obvious workaround here today.
Instead, we would presumably write
```ts
const p = {
a: 0,
b: "hello",
x: 8 // Should error, 'x' isn't in 'Keys'
} satisfies Partial<Record<Keys, unknown>>;
// using 'Partial' to indicate it's OK 'd' is missing
```
### Property Name Fulfillment
Same as Property Name Constraining, except we might want to ensure that we get *all* of the keys:
```ts
type Keys = 'a' | 'b' | 'c' | 'd';
const p = {
a: 0,
b: "hello",
c: true
// Should error because 'd' is missing
};
// Should be OK
const t: boolean = p.c;
```
The closest available workaround is:
```ts
const dummy: Record<Keys, unknown> = p;
```
but this assignment a) has runtime impact and b) will not detect excess properties.
Instead, we would presumably write
```ts
const p = {
a: 0,
b: "hello",
c: true
// will error because 'd' is missing
} satisfies Record<Keys, unknown>;
```
### Property Value Conformance
This is the flipside of Property Name Constraining - we might want to make sure that all *property values* in an object conform to some type, but still keep record of which keys are present:
```ts
type Facts = { [key: string]: boolean };
declare function checkTruths(x: Facts): void;
declare function checkM(x: { m: boolean }): void;
const x = {
m: true
};
// Should be OK
checkTruths(x);
// Should be OK
fn(x);
// Should fail under --noIndexSignaturePropertyAccess
console.log(x.z);
// Should be OK under --noUncheckedIndexedAccess
const m: boolean = x.m;
// Should be 'm'
type M = keyof typeof x;
// Should be able to detect a failure here
const x2 = {
m: true,
s: "false"
};
```
Another example
```ts
export type Color = { r: number, g: number, b: number };
// All of these should be Colors, but I only use some of them here.
export const Palette = {
white: { r: 255, g: 255, b: 255},
black: { r: 0, g: 0, d: 0}, // <- oops! 'd' in place of 'b'
blue: { r: 0, g: 0, b: 255 },
};
```
Here, we would presumably write
```ts
const Palette = {
white: { r: 255, g: 255, b: 255},
black: { r: 0, g: 0, d: 0}, // <- error is now detected
blue: { r: 0, g: 0, b: 255 },
} satisfies Record<string, Color>;
```
### Ensure Interface Implementation
We might want to leverage type inference, but still check that something conforms to an interface and use that interface to provide contextual typing:
```ts
type Movable = {
move(distance: number): void;
};
const car = {
start() { },
move(d) {
// d should be number
},
stop() { }
};
```
Here, we would presumably write
```ts
const car = {
start() { },
move(d) {
// d: number
},
stop() { }
} satisfies Moveable;
```
### Optional Member Conformance
We might want to initialize a value conforming to some weakly-typed interface:
```ts
type Point2d = { x: number, y: number };
// Undesirable behavior today with type annotation
const a: Partial<Point2d> = { x: 10 };
// Errors, but should be OK -- we know x is there
console.log(a.x.toFixed());
// OK, but should be an error -- we know y is missing
let p = a.y;
```
### Optional Member Addition
Conversely, we might want to safely initialize a variable according to some type but retain information about the members which aren't present:
```ts
type Point2d = { x: number, y: number };
const a: Partial<Point2d> = { x: 10 };
// Should be OK
a.x.toFixed();
// Should be OK, y is present, just not initialized
a.y = 3;
```
### Contextual Typing
TypeScript has a process called *contextual typing* in which expressions which would otherwise not have an inferrable type can get an inferred type from context:
```ts
// a: implicit any
const f1 = a => { };
// a: string
const f2: (s: string) => void = a => { };
```
In all of the above scenarios, contextual typing would always be appropriate. For example, in *Property Value Conformance*
```ts
type Predicates = { [s: string]: (n: number) => boolean };
const p: Predicates = {
isEven: n => n % 2 === 0,
isOdd: n => n % 2 === 1
};
```
Contextually providing the `n` parameters a `number` type is clearly desirable. In most other places than parameters, the contextual typing of an expression is not directly observable except insofar as normally-disallowed assignments become allowable.
## Desired Behavior Rundown
There are three plausible contenders for what to infer for the type of an `e satisfies T` expression:
* `typeof e`
* `T`
* `T & typeof e`
*SATA: Same As Type Annotation - `const v = e satisfies T` would do the same as `const v: T = e`, thus no additional value is provided
|Scenario|`T`|`typeof e`|`T & typeof e`|
|--------|---|----------|--------------|
|Safe Upcast|✔|❌ (undoes the upcasting)|❌ (undoes the upcasting)|
|Property Name Constraining|❌ (SATA)|✔|✔|
|Property Name Fulfillment|❌ (SATA)|✔|✔|
|Ensure Interface Implementation|❌ (SATA)|✔|✔|
|Optional Member Conformance|❌ (SATA)|✔|❌ (members appear when not desired)|
|Optional Member Addition|❌ (SATA)|❌ (members do not appear when desired)|✔|
|Contextual Typing|✔|✔|✔|
### Discussion
Given the value of the other scenarios, I think *safe upcast* needs to be discarded. One could imagine other solutions to this problem, e.g. marking a particular variable as "volatile" such that narrowings no longer apply to it, or simply by having better side-effect tracking.
### Excess Properties
A sidenote here on excess properties. Consider this case:
```ts
type Point = {
x: number,
y: number
};
const origin = {
x: 0,
y: 0,
z: 0 // OK or error?
} satisifes Point;
```
Is `z` an excess property?
One argument says yes, because in other positions where that object literal was used where a `Point` was expected, it would be. Additionally, if we want to detect typos (as in the *property name constraining* scenario), then detecting excess properties is mandatory.
The other argument says no, because the point of excess property checks is to detect properties which are "lost" due to not having their presence captured by the type system, and the design of the `satisfies` operator is specifically for scenarios where the ultimate type of all properties *is* captured somewhere.
I think on balance, the "yes" argument is stronger. If we don't flag excess properties, then the *property name constraining* scenario can't be made to work at all. In places where excess properties are expected, `e satisfies (T & Record<string, unknown>)` can be written instead.
However, under this solution, producing the expression type `T & typeof e` becomes very undesirable:
```ts
type Point2d = { x: number, y: number };
const a = { x: 10, z: 0 } satisfies Partial<Point2d> & Record<string, unknown>;
// Arbitrary writes allowed (super bad)
a.blah = 10;
```
Side note: It's tempting to say that properties aren't excess if all of the satisfied type's properties are matched. I don't think this is satisfactory because it doesn't really clearly define what would happen with the asserted-to type is `Partial`, which is likely common:
```ts
type Keys = 'a' | 'b' | 'c';
// Property 'd' might be intentional excess *or* a typo of e.g. 'b'
const v = { a: 0, d: 0 } satisfies Partial<Record<Keys, number>>;
```
Producing `typeof e` then leads to another problem...
### The Empty Array Problem
Under `--strict` (specifically `strictNullChecks && noImplicitAny`), empty arrays in positions where they can't be Evolving Arrays get the type `never[]`. This leads to some somewhat annoying behavior today:
```ts
let m = { value: [] };
// Error, can't assign 'number' to 'never'
m.value.push(3);
```
The `satisfies` operator might be thought to fix this:
```ts
type BoxOfArray<T> = { value: T[] };
let m = { value: [] } satisfies BoxOfArray<number>
// OK, right? I just said it was OK?
m.value.push(3);
```
However, under current semantics (including `m: typeof e`), this still doesn't work, because the type of the array is still `never[]`.
It seems like this can be fixed with a targeted change to empty arrays, which I've prototyped at #47898. It's possible there are unintended downstream consequences of this (changes like this can often foul up generic inference in ways that aren't obvious), but it seems to be OK for now.
## TL;DR
It seems like the best place we could land is:
* Contextually type empty arrays
* Disallow excess properties (unless you write `T & Record<string, unknown>`)
* Use `typeof e` as the expression type instead of `T` or `T & typeof e`
Does this seem right? What did I miss?
|