Skip to content
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

It is recommended that type assertions work on the variables themselves #17772

Closed
zhmushan opened this issue Aug 14, 2017 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@zhmushan
Copy link

zhmushan commented Aug 14, 2017

TypeScript Version: 2.4.0

interface I {
    data: string
}
let a: any = {data: 'string'}
a as I
a.da  // Now it should be wrong
a.data  // There should be smart tips here

We want the type assertion to work on the variable itself in the code block

@jcalz
Copy link
Contributor

jcalz commented Aug 15, 2017

Related to #17760?

What I do:

Helper function:

function assert<T>(x: any): x is T {
  return true;
}

Then:

interface I {
    data: string
}
let a: any = {data: 'string'}
if (!assert<I>(a)) throw null; // like "a as I"
a.da  // error
a.data  // smart tips galore

@zhmushan
Copy link
Author

zhmushan commented Aug 15, 2017

@jcalz This method is valid
But converted to Javascript,some become redundant

function assert(x) {
    return true;
}
var a = { data: 'string' };
if (!assert(a))
    throw null; // like "a as I"
a.da; // error
a.data; // smart tips galore

if expression will always be correct, it becomes an extra code with assert()
I think your method is similar:

interface I {
    data: string
}
let a: any = {data: 'string'}
let b: I = a

Both of these methods will generate extra Javascript code

Is it possible to have a method that only plays the role of type assertions in the Typescript, without generating extra JavaScript code

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 15, 2017
@RyanCavanaugh
Copy link
Member

Duplicate of #10421

@RyanCavanaugh RyanCavanaugh marked this as a duplicate of #10421 Aug 15, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants