-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Proposal] Type assertion statement (type cast) at block-scope level #10421
Comments
Technically we could just consider But I can still imagine something that says "assume the type of this entity is so-and-so for this block". |
That would be nice if the interface A {
x: number;
z: number;
}
interface B {
y: number;
z: number;
}
interface C {
x: number;
y: number;
}
type Union = A | B | C;
function check(obj: Union): void {
if ("x" in obj && "z" in obj) {
// obj is now treated as an instance of type A
}
else if ("y" in obj && "z" in obj) {
// obj is now treated as an instance of type B
}
else if ("x" in obj && "y" in obj) {
// obj is now treated as an instance of type C
}
} If such a case with combination of |
This looks like the same concept as #9946, but with different syntax. |
@yortus Thanks for the reference. Yes, I am glad I am not the only one who felt the need of such a concept even though the previous proposal insisted on type narrowing. What I propose is more than type narrowing, but type overcasting. let obj: A; // Type of obj is A
// ...
assume obj is B; // Type of obj is B
// ... This is would not only apply to type narrowing, but also to type casting. As said before, we could consider this proposal as a way to type cast an identifier at a block-scope level. Thinking of that, I am wondering if this could not be better to use |
So what you are really proposing is a type assertion statement that is otherwise exactly like the existing type assertion expression. For example: function fn(arg: P) {...}
// Type assertion as an expression (existing syntax)
let x: Q;
f(x as P); // 'x as P' is a type assertion expression
// Type assertion as a statement (proposed new syntax)
let y: Q;
assume y is P; // this is a type assertion statement
f(y); // y has type P here As with other statement/expression equivalences, this proposed new form of type assertion is used for its side-effects rather than its result, although obviously these are compile-time side-effects, since type assertions are elided at runtime. And as you mention you want the side-effects limited to the block in which the assertion appears. |
@yortus I like your distinction between statement and expression. So yes, type assertion statement is probably the best way to name this proposal. Syntactic possibilities:1. As suggested in #9946: 2. My primary proposal: 3. Type assertion statement syntax: 4. Short syntax A: 5. Short syntax B: let obj: any;
obj as number; // Type assertion expression So my preference goes for syntax (3): Extra notes
let obj: A; // Type of obj is A
...
assume obj as B; // Type of obj is B
...
assume obj as C; // Type of obj is C
... |
For reference, the spec on type assertion expressions (section 4.16) is here. The rules and use-cases described there for type assertions would presumably apply to this proposal in exactly the same way. |
BTW I see you're only proposing this to work on simple identifiers, whereas type assertion expressions work on arbitrary expressions, like |
In my mind, |
@yahiko00 User defined type guard functions actually are an important part of the emitted code. They may determine control flow at runtime. Also this is not type inference, it is type assertion (or type assumption 😛 ). If you want shorthand type guards you can write function is<T>(value, condition: boolean): value is T {
return condition;
} then you can write the following function processGeometry(obj: Geometry): void {
if (is<AARect>(obj, "width" in obj)) {
let width = obj.width;
// ...
}
if (is<AABox>(obj, "halfDimX" in obj)) {
let halfDimX = obj.halfDimX;
// ...
}
else if (is<Circle>(obj, "radius" in obj)) {
let radius = obj.radius;
// ...
}
} |
I do not deny the usefulness of type guard functions. But there are cases where I do not want type guards functions. First, as expressed before, because it adds verbosity where it is not needed. Your workaround above is interesting but adds a layer of abstraction, which is less clear than a plain test |
Fair enough. |
@aluanhaddad |
@yortus that's an excellent point |
Consider using a discriminated union with a type literal https://basarat.gitbooks.io/typescript/content/docs/types/discriminated-unions.html 🌹 |
That is true. |
FWIW I asked for this a long time ago but once we got let/const I've just done the following (before discriminated unions): interface AARect {
x: number; // top left corner
y: number; // top left corner
width: number;
height: number;
}
interface AABox {
x: number; // center
y: number; // center
halfDimX: number;
halfDimY: number;
}
interface Circle {
x: number; // center
y: number; // center
radius: number;
}
type Geometry = AARect | AABox | Circle; // ... And much more
function processGeometry(obj: Geometry): void {
if ("width" in obj) {
let objT = obj as AARect;
let width = objT.width;
// ...
}
if ("halfDimX" in obj) {
let objT = obj as AABox;
let halfDimX = objT.halfDimX;
// ...
}
else if ("radius" in obj) {
let objT = obj as Circle;
let radius = objT.radius;
// ...
}
// And much more...
} 🌹 |
Logged #10485 because we always prefer to just have narrowing happen automatically. We've wanted a syntactic space for this for a while but haven't found anything that isn't ugly or looks like an expression with side effects. |
I found an absurd workaround for this issue. For some reason, using a In fact, this could be a possible syntax if this suggestion were to be implemented, since it doesn't create any new keywords. interface A {
x: number;
z: number;
}
interface B {
y: number;
z: number;
}
interface C {
x: number;
y: number;
}
type Union = A | B | C;
function check(obj: Union): void {
if ("x" in obj && "z" in obj) {
// @ts-ignore
declare let obj: A
// obj is now treated as an instance of type A
}
else if ("y" in obj && "z" in obj) {
// @ts-ignore
declare let obj: B
// obj is now treated as an instance of type B
}
else if ("x" in obj && "y" in obj) {
// @ts-ignore
declare let obj: C
// obj is now treated as an instance of type C
}
} EDIT: This only works in a new scope, for example inside a block. Usually, since this is useful to augment type narrowing, this is not an issue. However, casting variables such as function arguments using |
@EnderShadow8 this is interesting 🙂 I did some tests to see if I could break it, but it seems to work - my main worry was the redeclared types would somehow leak to the I couldn't find any gotchas - is this really as simple as just lifting the restriction and allowing what already works? 🤷♂️ It should probably still have a dedicated syntax though, since If nothing else, this makes for a pretty nifty workaround. 😃👍 EDIT: the only caveat I can find is the fact that the new symbol is just that: a new symbol, shadowing the symbol on the parent block scope - which means, your inner So the risk of doing this, is it will break if you rename or remove the parent symbol - and emit code that fails. |
Just wanted to drop another use case for this that I documented on StackOverflow. I came up with a similar solution as @MattiasBuelens's |
FWIW, I'd be surprised if even the most basic optimizer can't recognize and eliminate calls to a no-op function:
|
@shicks No but you can easily end up with a case where maybe the function call is eliminated but the argument is not due to the possibility of side effects.
|
I just use |
I think that this issue can be closed because Typescript already narrows the type correctly (at least since version 3.3, which is the last one that we can test in the playground). |
I love this idea. This thread is really long but what're the current blockers? |
With the new interface AOptional {
a?: number,
// ...
}
interface ARequired {
a: number,
newProp?: string,
// ...
}
function convertToARequiredInPlace(obj: AOptional): ARequired {
obj.a ??= 0;
obj satisfies ARequired; // this currently fails but the compiler could see that the line above fixes that
// then TS could start treating obj as ARequired and these would both be allowed
obj.newProp = "foo";
return obj;
} |
Why hasn't this been included for so many years? Reanimated in React-Native really could use it - we have to face multiple architectures, platforms and it would be nice if after checking what platform we are on we could inline type guard some parameters to be platform specific. Since performance is key for us even a couple type guard calls can be too expensive and multiple type assertions are just cluttering the code. |
If you write a no-op type guard, you shouldn't see any performance regression. Nearly every VM will do JIT optimization to inline the empty function call into the calling functions' bytecode. The only exception I'm aware of is iOS native, which doesn't allow it, but in that case you're already bundling, and every bundler can (and will) also inline empty functions in production builds. Such an empty type guard isn't particularly "safe" (since it's not actually doing any checking at runtime), but depending on how you type it, it's no less safe than an ordinary |
Also, you can get 90% of the way there with |
@shicks variable is Type; seems to be much more informative than noopAssertJustToConfirmScopeType(variable); But of course the function can be named better etc. and some guidelines can be added, so that's just an opinion. Unfortunately, we cannot exactly rely on JIT optimizations since what we actually do is copying JS functions in between JS runtimes via their code (as a string). I know it sounds dumb, but currently it's the only option we have, since we must do it in runtime. We are looking into the possibility of having this code copied before the runtime is started, so we could actually have those JIT optimizations (along many other things) included, but at the moment we aren't exactly sure if it's feasible and it requires effort not only from us but also from folks from React Native. Maybe this comes from my misunderstanding of how TypeScript should be used - I always considered it to be an augmentation of JavaScript - that means, if I have a JS function that is dynamically type safe, I can make its TypeScript counterpart statically type-safe, compile it and get exactly the same code as the original JS function. If that's not the mission of TypeScript, I'm completely fine with that and the feature proposed here isn't necessary. @dead-claudia From time to time we have some really "dense" core functions, some algorithms that are very concise and have to take into account various platforms. Once you know the code there's no problem skipping You might argue that in this case the function is poorly written in TypeScript - and I agree with you, back in the day, the code was purely JS and rewriting it into TS wasn't the simplest of tasks. I try to tackle down such functions and rewrite them to be of equivalent performance and behavior but with better types. However, since they are core functions, it requires a lot of attention from the whole team to make sure there aren't any regressions involved in those type of refactors, since there are many little details that could be overlooked. Therefore such inline type guards would be a good QoL addition. |
@tjzel I agree 100% that something like this in the language would be amazing- our comments are almost 1 to 1 (see earlier in the thread). I've found that this is probably the simplest way to do this as of now: function cast<T>(it: any): T {
return it;
}
function castTest() {
const testObject = {
color: "red",
};
// asString is now a string type (obviously bad though)
const asString = cast<string>(testObject);
} The syntax isn't so bad- and feels natural enough. const color = cast<Color>(someColorThing); But yea, having to do this could be dangerous overall and remove some of the type safety that TypeScript gives to us. But there definitely are places where this comes in handy (not every project is greenfield). |
@lostpebble your last workaround doesn't really address this. The whole purpose of this issue is to make an existing variable be inferred as a different type, not create a new variable nor make function calls that impact runtime. Otherwise the simplest is:
But again, the whole purpose is to avoid that runtime change entirely. |
Just sharing another scenario where this would be super helpful - receiving an object as a parameter, extending it, and then returning it as the new type, without assigning any new variables. Given a scenario of building a JSON response, this is currently my code: export async function assign_file_url<F extends FileProperties>(file: F) {
if (file.kind === 'file') {
// @ts-expect-error: 'url' does not exist, type is cast at return
file.url = await storage.bucket(file.bucketId).presignGetUrl(file.publicId);
} else {
// @ts-expect-error: 'url' does not exist, type is cast at return
file.url = null;
}
return file as F & { url: string | null };
} And this could be the code after an "assume" keyword is introduced. export async function assign_file_url<F extends FileProperties>(file: F) {
assume file as F & { url: string | null };
if (file.kind === 'file') {
file.url = await storage.bucket(file.bucketId).presignGetUrl(file.publicId);
} else {
file.url = null;
}
return file;
} |
@oscarhermoso I don't think a new keyword is needed, as the keyword // Feedback, not valid
const value: number | Object ...
if (Number.isNumber(value)) {
value satisfies number
console.log(2 + value)
} else {
console.log('value is an object')
} |
interface Circle {
radius: number;
x: number;
y: number;
}
const circlePlus =
{x: 0, y: 0, radius: 1, color: "red"} as const;
// Errors if you remove x, y, or radius properties
circlePlus satisfies Circle; The |
Yeah, this seems more like a declaration as I've suggested before. This is already valid: declare let value: number;
function lol() {
const n = value + 1;
} My intuition was always that declarations would "just work" in scopes: function lol() {
declare let value: number;
const n = value + 1;
} It's already syntax that can be parsed - it just doesn't mean anything. (an earlier request had a nice approach to the syntax, and avoided shadowing, as mentioned in my previous comment.) |
I would love to see inline/block-scope type guards (I didn't know the right words for this stuff when I posted on Twitter). This is probably the thing I run into in TypeScript that is most annoying - automatic type narrowing is really cool but has many obvious limits, and type guards having to be functions makes them too cumbersome for common use cases. In my ideal world there would be a mechanism to accomplish two things simultaneously:
This is the kind of code I don't like: if ((foo as any)?.someProperty) {
const fooCast = foo as ThingWithSomeProperty;
// ... code here
} What I'd prefer to write is something like: if (foo?.someProperty): foo is ThingWithSomeProperty {
// ... code here
} |
This is a proposal in order to simplify the way we have to deal with type guards in TypeScript in order to enforce the type inference.
The use case is the following. Let us assume we have dozens (and dozens) of interfaces as the following:
Code
And we have a union type like this one:
It is quite easy to discriminate a type from another with
hasOwnProperty
or thein
keyword:But, as we can see, this is quite burdensome when we need to manipulate
obj
inside eachif
block, since we need to type cast each time we useobj
.A first way to mitigate this issue would be to create an helper variable like this:
But this is not really satisfying since it creates an artefact we will find in the emitted JavaScript file, which is here just for the sake of the type inference.
So another solution could be to use user-defined type guard functions:
But again, I find this solution not really satisfying since it still creates persistent helpers functions just for the sake of the type inference and can be overkill for situations when we do not often need to perform type guards.
So, my proposal is to introduce a new syntax in order to force the type of an identifier at a block-scope level.
Above, the syntax
assume <identifier> is <type>
gives the information to the type inference that inside the block, following this annotation,<identifier>
has to be considered as<type>
. No need to type cast any more. Such a way has the advantage over the previous techniques not to generate any code in the emitted JavaScript. And in my opinion, it is less tedious than creating dedicated helper functions.This syntax can be simplified or changed. For instance we could just have :
<identifier> is <obj>
without a new keyword
assume
, but I am unsure this would be compliant with the current grammar and design goals of the TypeScript team.Nevertheless, whatever any welcomed optimization, I think the general idea is relevant for making TypeScript clearer, less verbose in the source code and in the final JavaScript, and less tedious to write when we have to deal with union types.
The text was updated successfully, but these errors were encountered: