How to convert string to interface type in angular?

Active3 hr before
Viewed126 times

7 Answers


Convert Angular TypeScript examples into ES6 and ES5 JavaScript,,TypeScript to JavaScript,Most Angular TypeScript and ES6 code is written as classes

Example_snippet/controller/utility/_angular.js/ import { platformBrowserDynami. . .
import {
} from '@angular/platform-browser-dynamic';
import {
} from '@angular/common';
load more v

String JSON text to Typescript class or interface object,Typescript is a superset of javascript with type assertions feature, In javascript, we have used JSON

Example_snippet/controller/utility/_angular.js/ let employee = '{"name": "Fran. . .
let employee = '{"name": "Franc","department":"sales","salary":5000}';
load more v

A newer version of this site just became available, Please refresh this page to activate it

Example_snippet/controller/utility/_angular.js/ type Pizza = { name: string;. . .
type Pizza = {
   name: string;
   size: string[];
load more v

Convert Existing JavaScript to TypeScript ,The TypeScript compiler does not convert interface to JavaScript, It uses interface for type checking

Example_snippet/controller/utility/_angular.js/ interface IEmployee { empC. . .
interface IEmployee {
   empCode: number;
   empName: string;
   getSalary: (number) => number; // arrow function
   getManagerName(number): string;
load more v

We can write the same example again, this time using an interface to describe the requirement of having the label property that is a string:,The type checker checks the call to printLabel, The printLabel function has a single parameter that requires that the object passed in has a property called label of type string

Example_snippet/controller/utility/_string.js/ tsfunction printLabel(labeledO. . .
tsfunction printLabel(labeledObj: {
   label: string
}) {
let myObj = {
   size: 10,
   label: "Size 10 Object"
load more v

Example_snippet/controller/utility/_string.js/ var x = "32"; var y: number = . . .
var x = "32";
var y: number = +x; //the "+" converts string to number

Thanks for contributing an answer to Stack Overflow!,I have store value in local storage then I need this local storage value to store in interface type variable, but showing error as can not string to the interface type

Example_snippet/controller/utility/_string.js/ export function hydrateFromLoc. . .
export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    return JSON.parse(localStorage.getItem(key))
  catch (error) {
    return null;

// example
const currentUser = hydrateFromLocalStorage<YourInterface>('currentUser');