Typescript cast any to type

Typescript cast any to type

It will raise errors when something is of type where there wasn’t an explicit type annotation. Whenever TypeScript sees something without a type annotation where its type can’t be inferred, it’s going to use because that’s the type that lets the most JavaScript compile without errors.

Typescript cast any to type

import < useState, useEffect >from 'react' interface GeoLocationData < isGeoLocationDataSet: boolean lat: string lon: string errorCode: number, errorMsg: string >export const Test = (): GeoLocationData => < const [geoLocationData, setGeolocationData] = useState(< isGeoLocationDataSet: false, lat: '', lon: '', errorCode: 0, errorMsg: '' >); // stuff here return geoLocationData > 

geoLocationData is not cast to type GeoLocationData when used in another component:

import React from 'react'; import './App.css'; import < Test>from './hooks/Test'; function App() < const geoLocation = Test return ( ); > export default App; 
Property 'isGeoLocationDataSet' does not exist on type '() => GeoLocationData'.ts(2339) 

But isGeoLocationDataSet does exist as a prop in GeoLocationData .

export const Test = (): GeoLocationData => (< const [geoLocationData, setGeolocationData] = useState(< isGeoLocationDataSet: false, lat: '', lon: '', errorCode: 0, errorMsg: '' >); // stuff here return geoLocationData >) 
Type '< const: [GeoLocationData, React.Dispatch>]; return: any; >' is not assignable to type 'GeoLocationData'. Object literal may only specify known properties, and 'const' does not exist in type 'GeoLocationData'. 

Test is a function, so you need to call it to get the returned value of type GeoLocationData :

Читайте также:  Python work with pdf

TypeScript Casting, This type of casting will not work with TSX, such as when working on React files. w 3 s c h o o l s C E R T I F I E D. 2 0 2 2 Get Certified! Complete the TypeScript modules, do the exercises, take the exam and become w3schools certified!! $95 ENROLL. Force casting. To override type errors that TypeScript may throw when …

TypeScript: Implicit cast from any to everything?

I’m just learning TypeScript and I’m a bit perplexed about the nature of any . Take a look at this:

var x: any = 1; var y = 1; x = y; y = x; // why does this not cause a compile-time error? 

At first I understood any to be the type without any promises — which is why the first assignment is reasonable to work — but it appears that in other contexts (the second assignment), it can be a type with all conceivable promises.

For example, this piece of insanity also compiles just fine:

That’s because undefined is assumed to be any , which is a type promising everything. Hmmm.

var a : HTMLElement = new HTMLDivElement(); var b = new HTMLDivElement(); a = b; b = a; // doesn't compile. phew. 

Here we get what I would expect from assigning a more general thing to a more special thing in a strongly typed language: An error, as an explicit cast would be necessary:

b = a; // ah, you mean it's really a div. 

In most cases where any is used, I would expect something like unknown , defined as

I first came across this problem as my code was using eval to parse json. eval returns any , which means that TypeScript thinks that you can do everything with it, without any casts.

I think that’s clearly wrong. Compare that issue to factories in other typed languages, such as C#:

(MyType)Activator.Create(typeof(MyType)) // cast is needed 
// cast is needed in C++ (not in C, though I think it really should. ) (MyType*)malloc(size); 

Whenever I have a function that produces something untyped, I would expect that I need to cast it before I can use it for anything.

  1. Is there the analogous to any , something like the above unknown , that is standard?
  2. If so, why is any featured so prominently and the other so hidden?
  3. Has this issue been raised somewhere? Is there a discussion anyone can link to?

To the first question, the equivalent to unknown is <> , the empty type. The compiler will sometimes produce <> when no other type can be computed (for example, in [‘foo’, 42] , the element type was <> before it became string|number with the addition of union types).

Next, the reason any is often mentioned is that the typical complaint about TypeScript is that it has too much type enforcement, rather than too little. JavaScript programmers just don’t seem to be in to writing typecasts all the time. Obviously this is a matter of taste, but it is what it is.

This is all very much by design because a core scenario for TypeScript is to take an existing piece of JavaScript and add exactly as much type information as you want without getting tons and tons and tons of errors. Whenever TypeScript sees something without a type annotation where its type can’t be inferred, it’s going to use any because that’s the type that lets the most JavaScript compile without errors.

The undefined.foo thing was fixed in version 1.1. It now correctly reports an error (the exact treatment of undefined and null in TypeScript is an interesting but separate discussion).

As Steve mentions, noImplicitAny is there to help. It will raise errors when something is of type any where there wasn’t an explicit type annotation.

The any type is a special type. Where possible, you should avoid using the any type unless you want to take advantage of dynamic types.

The any type is a short way of saying.

Treat this variable as if it were compatible with any other type.

So you can assign it to a string, a number, an array, an object, a interface with any structure. anything at all.

So don’t think of it as being an any type, think of it as being «a string if I assign it to a string «.

You can avoid accidental use of the any type by passing the —noImplicitAny compiler flag (or setting your project settings to use this flag).

How to correctly type and cast a generic in TypeScript?, The issue is in the way the generic is defined, the = operator assigns a default type which will probably never happen because it is always inferred by TS from the argument of type Obj.What would fix it here is to use the extend operator which will constrain the argument to extend the interface provided.. like this: // …

Why can’t I cast from any[] to MyType[] in TypeScript?

TypeScript has an any type that any and every arbitrary type can be cast TO OR FROM. I can cast from a variable of type any to a variable of type MyArbitraryType like in

var myThing: MyArbitraryType; var anyThing: any; . myThing = anyThing;//implicit cast from 'any' to 'MyArbitraryType' //or myThing = anyThing;//explicit cast from 'any' to 'MyArbitraryType' 

But I get an error when I try to cast from an any[] to a MyArbitraryType[] like in

var myThings: MyArbitraryType[]; var anyThings: any[]; . myThings = anyThings;//implicit cast from 'any[]' to 'MyArbitraryType[]' //or myThings = anyThings;//explicit cast from 'any[]' to 'MyArbitraryType[]' 

However I CAN do it if I use any as a middle-man like in

Which I could just use as is, but feels kinda sloppy. Is there a reason that any is castable to and from any type but any[] isn’t castable to and from any array? Is this just an oversight in TypeScript so far? Or is there some other syntax I’m unaware of?

False alarm. It was Resharper, not the actual Typescript compiler, that was generating the error.

TypeScript: Implicit cast from any to everything?, To the first question, the equivalent to unknown is <>, the empty type. The compiler will sometimes produce <> when no other type can be computed (for example, in [‘foo’, 42], the element type was <> before it became string|number with the addition of union types). Next, the reason any is often mentioned is that the …

Why can ‘any’ be assigned to any type without explicitly casting it first?

Why is the following code snippet not raising any errors or warnings?

My expectations are: anything should be assigned to y as it is explicitly typed as any , but only numbers should be assigned to x as it is explicitly typed as number and if an any needs to be assigned to x then that should be explicitly cast to number :

How could the current behaviour considered to be acceptable or as a good idea and not a bug in the first place? Moreover, is there a way to force the compiler to raise an issue about this and only accept explicit casting?

This is the defined behavior of any . This type is at the same type :

  • Assignable from any other type
  • Assignable to any other type (the issue you highlight)
  • Any operation is allowed with it (indexing, calling, property access, operator application, all are allowed and not checked in any way)

There several uses for any . A couple of examples:

  • Allow easy transition from js to ts. While you are converting the code to typescript any can be very useful to allow you to compile the code successfully while you are still converting.
  • Allow easy interop with existing JS code (just type something as any and you can use it as you would in JS). Although you are probably better off writing definitions in the long run.

All this being said, I would avoid any at all cost in Typescript today. Typescript 3.0 introduces the unknown type which behaves like you expect any to behave (ie, you can assign anything to it but it is not assignable to any other type). Read more about unknown here

A few options to rid yourself of any :

  • noImplictAny compiler setting prevents the compiler from inferring any if you don’t specify a type (it will issue an error instead)
  • no-unsafe-any tslint rule, prevents uses of any in a dynamic way, ie uses are only allowed if they would work for <> | null | undefined
  • no-any tslint rule, prevents any and all uses of any

Javascript — TypeScript cast using «as», 1 Answer. Casting — or more properly, type assertion — is not conversion/coercion. It has no runtime effect in TypeScript.¹ It’s just the process of telling TypeScript that a variable or property is of the type you’re casting it to asserting. In your first example, a gets the exact same value that myType has in …

Источник

Type Casting

Summary: in this tutorial, you will learn about type castings in TypeScript, which allow you to convert a variable from one type to another type.

JavaScript doesn’t have a concept of type casting because variables have dynamic types. However, every variable in TypeScript has a type. Type castings allow you to convert a variable from one type to another.

In TypeScript, you can use the as keyword or <> operator for type castings.

Type casting using the as keyword

The following selects the first input element by using the querySelector() method:

let input = document.querySelector('input["type="text"]');Code language: TypeScript (typescript)

Since the returned type of the document.querySelector() method is the Element type, the following code causes a compiler error:

console.log(input.value);Code language: TypeScript (typescript)

The reason is that the value property doesn’t exist in the Element type. It only exists on the HTMLInputElement type.

To resolve this, you can use type casting that cast the Element to HTMLInputElement by using the as keyword like this:

let input = document.querySelector('input[type="text"]') as HTMLInputElement;Code language: TypeScript (typescript)

Now, the input variable has the type HTMLInputElement . So accessing its value property won’t cause any error. The following code works:

console.log(input.value); Code language: TypeScript (typescript)

Another way to cast the Element to HTMLInputElement is when you access the property as follows:

let enteredText = (input as HTMLInputElement).value;Code language: TypeScript (typescript)

Note that the HTMLInputElement type extends the HTMLElement type that extends to the Element type. When you cast the HTMLElement to HTMLInputElement , this type casting is also known as a down casting.

It’s also possible to carry an down casting. For example:

let el: HTMLElement; el = new HTMLInputElement();Code language: TypeScript (typescript)

In this example, the el variable has the HTMLElement type. And you can assign it an instance of HTMLInputElement type because the HTMLInputElement type is an subclass of the HTMLElement type.

The syntax for converting a variable from typeA to typeB is as follows:

let a: typeA; let b = a as typeB; Code language: TypeScript (typescript)

Type Casting using the <> operator

Besides the as keyword, you can use the <> operator to carry a type casting. For example:

let input = document.querySelector('input[type="text"]'); console.log(input.value); Code language: TypeScript (typescript)

The syntax for type casting using the <> is:

let a: typeA; let b = a; Code language: TypeScript (typescript)

Summary

  • Type casting allows you to convert a variable from one type to another.
  • Use the as keyword or <> operator for type castings.

Источник

Оцените статью