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

Why is there no error when type assertion fails??? #49436

Closed
fanybook opened this issue Jun 8, 2022 · 3 comments
Closed

Why is there no error when type assertion fails??? #49436

fanybook opened this issue Jun 8, 2022 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@fanybook
Copy link

fanybook commented Jun 8, 2022

Suggestion

There should be an error when the type assertion fails

typescript

let str: unknown = 'hello'
str = 666 // or str = null

let newStr:string = <string>bb

console.log(typeof newStr) // number
console.log(newStr) // 666

let slice = (<string>bb).split(',') // Error
console.log(slice)​

golang

var str interface{} =hellostr = 666

// newStr, ok :=  str.(string) // ok is false
newStr :=  str.(string) // Error

// string operation
@guillaumebrunerie
Copy link

guillaumebrunerie commented Jun 8, 2022

Because Typescript is not Go, <string>bb means "please consider bb as a string even if it isn’t". It does not (and cannot) check whether it is actually valid. When you use this notation, it's your responsibility for it to make sense. If you want runtime checks, you can write them using typeof.

See https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions

Reminder: Because type assertions are removed at compile-time, there is no runtime checking associated with a type assertion. There won’t be an exception or null generated if the type assertion is wrong.

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Jun 8, 2022
@fatcerberus
Copy link

For the record, the term "type assertion" is maybe a bit misleading - it's not an "assertion" in the same sense as assert(typeof foo === 'string') - it's you asserting that the value is actually the type you say, regardless of what the compiler currently thinks it is. You won't get a runtime error if you're wrong, because the type information is completely erased by the compiler.

@typescript-bot
Copy link
Collaborator

This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow or the TypeScript Discord community.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

5 participants