- Typescript: cast an object to other type. How? And instanceof or typeof?
- How about checking if an object is an instance of a given type?
- 4.19.4 The instanceof operator
- Since we’re at it, have you heard of the typeof operator?
- Share on
- Leave a Comment
- You May Also Enjoy
- Application Services Best Practices
- kubectl: export pod logs to file
- This feature requires ASM8_EXPERIMENTAL — task bootJar — Gradle/SpringBoot
- How to bind a Date object to an input date using vue.js? (v-model doesn’t work)
- Typescript: Cast an object to other type using. How? And instanceof or typeof?
- Typescript: Cast an object to other type using. How? And instanceof or typeof?
- How to cast to specific object type in Typescript?
- Typescript: How to cast or assign an object to a type with fewer properties? (From Big to Small)
- Type Assertion vs. Casting
- Type Assertion Example
- Example using Static Factory Functions
- Output
- How to cast object to another type and remove unneeded fields in TypeScript?
- Type Casting
- Type casting using the as keyword
- Type Casting using the <> operator
- Summary
Typescript: cast an object to other type. How? And instanceof or typeof?
How about checking if an object is an instance of a given type?
Glad you asked. This shouldn’t come as a big surprise, though, instanceof in TypeScript is similar to other popular languages:
if (myObject instanceof Type) console.log("myObject *is* an instance of Type!"); > else console.log("Oops! myObject is not an instance of Type. "); >
You can find more about it in the TypeScript Language Specification:
4.19.4 The instanceof operator
The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the ‘ Function ’ interface type. The result is always of the Boolean primitive type.
Note that object types containing one or more call or construct signatures are automatically subtypes of the ‘ Function ’ interface type, as described in section 3.3.
Since we’re at it, have you heard of the typeof operator?
Using the typeof operator, you can find out a variable’s type:
// Using typeof in an EXPRESSION: var x = 5; var y = typeof x; // y will have the string "number" as value // Using typeof in an TYPE QUERY // (or. as I like to say, variable declaration): var a = 9; // a is a number var b: typeof a; // b will be declared as a number as well b = "a string"; // yields an error, as b is a number: // "Type 'string' is not assignable to type 'number'."
Find more about typeof in the TypeScript spec as well.
Tags: casting , typescript
Categories: Typescript
Updated: March 20, 2016
Share on
Leave a Comment
You May Also Enjoy
Application Services Best Practices
Application services are an integral part of popular layered architectural styles, such as ports & adapters (hexagonal), onion architecture or clean arch.
kubectl: export pod logs to file
Say you have your kubernetes setup going and want to use kubectl to save/export the logs of a pod to a file.
This feature requires ASM8_EXPERIMENTAL — task bootJar — Gradle/SpringBoot
How to bind a Date object to an input date using vue.js? (v-model doesn’t work)
If you really want to use v-model you have to create a custom component (see below in the second part of this post).
Typescript: Cast an object to other type using. How? And instanceof or typeof?
Solution 1: You are asking typescript to modify value Typescript doesn’t run your code, only compiles and checks for type safety What you can do is: define null props to B class, and check keys Solution 2: From typescript deep dive A type assertion tells the Typescript compiler that you already know that a value may be safely treated as another type, even though it cannot be verified through static analysis. Example using Static Factory Functions Output Question: Suppose I have the following code: Now the variable has type , but it still contains inside of it.
Typescript: Cast an object to other type using. How? And instanceof or typeof?
Cast an object to other type using Typescript. How? And instanceof or typeof?
let object = myObject as string; // this way let object = myObject; // or this way
In addition, instanceof returns a boolean, typeof returns the instance type.
» Type Assertion » as this is called in Typescript can be done as follows:
interface Student < name: string; code: number; >let student = < >; //or < >as student student.name = "Rohit"; // Correct student.code = 123; // Correct
In the above example, we have created an interface Student with the properties name and code. Then, we used Type Assertion on the student, which is the correct way to use type assertion.
Use typeof for simple built in types:
true instanceof Boolean; // false typeof true == 'boolean'; // true
Use instanceof for complex built in types:
[] instanceof Array; // true typeof []; //object
Cast JSON object to interface ignoring case sensitivity in typescript, If you don’t have type definitions or you are going to manually recreate them anyway, just set the return type of your case modifying function to this type. You don’t need to …
How to cast to specific object type in Typescript?
I’m new to Typescript/React/rxJS ecosystem.
I use the following code snippet in my React/Typescript/rxJS application to download a list of users for my proof of concept work:
const githubUsers = `https://api.github.com/users?per_page=1`; const users$ = ajax.getJSON(githubUsers).pipe( map(response => < // @ts-ignore const user: User = response[0] as User; return user; >), catchError(error => throwError(error)) ); users$.subscribe( response => log.info("User response: ", response), error => log.error(error), () => log.info("Subscription completed.") );
The «log.info» is my custom built log framework, it can be replaced with «console.log» if you want to try it out.
If I leave the «ts-ignore», I have this problem:
TS2571: Object is of type 'unknown'. 72 | const users$ = ajax.getJSON(githubUsers).pipe( 73 | map(response => < >74 | const user: User = response[0] as User; | ^^^^^^^^ 75 | return user; 76 | >), 77 | catchError(error => throwError(error))
So, my question is how can I properly cast this?
I appreciate any help on this.
The problem is already in the logs 🙂
response object is unknown
so, on line 73, use Type assertion and create a temporary variable. Use that array variable later:
Learn How cast method works in TypeScript?, Surprisingly, typescript language that compiles into the programming language JavaScript has the concept of casting. In this article, we will be dealing with typecasting in the typescript …
Typescript: How to cast or assign an object to a type with fewer properties? (From Big to Small)
I have three Objects(Classes), they’re like following:
Now I have a JSON which is like:
I’m wondering if there is any clean way to cast class A to class B and class C ?
I tried this method, but after map , class B has all 5 properties from A instead of the 2 properties defined on B .
class B < public value1: string; public value2: string; constructor(item: A) < Object.assign(this, item); >> let arr1: A[]; let arr2 = arr1.map(item => new B(item));
You are asking typescript to modify value
Typescript doesn’t run your code, only compiles and checks for type safety
What you can do is: define null props to B class, and check keys
class A < public value1: string public value2: string public value3: string public value4: string public value5: string >class B < public value1: string = undefined // < // combine same keys if (thisKeys.includes(key)) < newObjTypescript cast object to any = itemTypescript cast object to any >return newObj >, <>) Object.assign(this, limitedItem) // asign to this class > > const arr1 = [< value1: '1', value2: '2', value3: '3', value4: '4', value5: '5' >] let arr2 = arr1.map(item => new B(item)) console.log('arr2', arr2) // arr2 [ B < value1: '1', value2: '2' >]
Type Assertion vs. Casting
The reason why it’s not called «type casting» is that casting generally implies some sort of runtime support. However, type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.
A type assertion tells the Typescript compiler that you already know that a value may be safely treated as another type, even though it cannot be verified through static analysis.
Type Assertion Example
Since type A and B do not overlap, the Typescript compiler will issue a warning if you try and assign an instance of A to a B .
let a = new A('a', 'b', 'c', 'd', 'e'); let b: B = a; // Error: Type 'A' is missing the following properties from type 'B': num1, num2
Using a Type Assertion, you could tell the compiler to ignore the mismatched types, which in this case is a bad idea.
let a = new A('a', 'b', 'c', 'd', 'e'); let b: B = a; let b2: B = a as any;
What you are asking is how to limit the properties that are assigned when copying an instance of a class that has more properties than the target class. In your example, a straightforward approach would be to create static factory functions (i.e. specialized constructors) for B and C that accept instances of A as shown below.
Example using Static Factory Functions
class A < constructor(public val1: string, public val2: string, public val3: string, public val4: string, public val5: string) <>> class B < constructor(public val1: string, public val2: string) <>static constructFromA(a: A): B < return new B(a.val1, a.val2); >> class C < constructor(public val3: string, public val4: string, public val5: string) <>static constructFromA(a: A): C < return new C(a.val3, a.val4, a.val5); >> let a = new A('a', 'b', 'c', 'd', 'e'); let b = B.constructFromA(a); let c = C.constructFromA(a); console.log(JSON.stringify(b, null, 2)); console.log(JSON.stringify(c, null, 2));
Output
// New B from A < "val1": "a", "val2": "b" >// New C from A
Best way to cast an object to a TypeScript Enum Value, Is there an easy/best practice way to cast an any value to a TypeScript Enum and throw an exception if there is no value. As an example You have an express request object …
How to cast object to another type and remove unneeded fields in TypeScript?
Suppose I have the following code:
interface A < a: number; >interface B extends A < b: number; >const b: B = ; const a: A = b as A;
Now the variable a has type A , but it still contains b inside of it. Sometimes it is undesirable — I’d like to be sure that, if I have a variable of type A , it has the exact fields of type A . I was wondering, whether TypeScript has some kind of a «hard cast» which would remove any unneeded fields when converting between types.
There is no casting in TypeScript because that’s not how TypeScript works. TS is a type layer on top of JS. When you assign a type in TS you don’t set a type, you annotate that the given expression is of a certain type. When the TS code is transpiled to JS, all type information is stripped.
Or in other words: the type system is JS, with TS you just announce that a variable is of a certain type. More often than never it happens that you assign the wrong type at design time and get suprised during debug that the variable has a completely different type than expected.
If you want to be sure that a property is removed from an object, you need to go the JS way (and — if necessary — annotate the result with TS). Check this Q&A to see how to remove properties from an object.
I originally didn’t plan on answering, but the reason I chose to answer because I feel like deleting the data in the original object might not always be a good idea.
Instead I think it’s better to create a new variable and copy the data (without the unneeded properties) to the new variable.
I my case, I wanted to cast my register form into login information (email & password) and other information (on how the found the website).
The following solution is fairly easy to use (in various situations) and easily expandible.
Cast object to interface in TypeScript, Then you can use it to force cast objects to a certain type: import < forceCast >from ‘./forceCast’; const randomObject: any = <>; const typedObject = forceCast
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.