xxxxxxxxxx
// The 'as' keyword asserts that a variable has a type. =>
// TypeScript throws an error if these types have no overlap.
// The following example will work with jQuery.
let inputElt = $("#text_input");
// type of inputElt is JQuery<HTMLElement>
let inputValue = inputElt.val();
// type of inputValue is string | string[] | null | undefined
// If we are sure that the input element is a valid element and is only
// present once, the value must be of type string.
// Thus we can assert it is a string, as so:
let inputValueAsString = inputValue as string;
// If you want to learn more, click the link in the source.
xxxxxxxxxx
interface Person {
name: string;
age: number;
}
const data: any = { name: 'John', age: 25, city: 'New York' };
// Using type assertion to tell TypeScript that data is a Person
const personData = data as Person;
// Now you can access properties as if data were a Person
console.log(personData.name); // 'John'
console.log(personData.age); // 25