I read many articles about TypeScript and couldn't find anything. What type to set for elements X and Y? or how to convert the code to TS? thanks in advance for your help
const x = document.getElementById("password-input");
const y = document.getElementById("img");
function showPass() {
if (x.type === "password") {
x.type = "text";
y.src = "png"
} else {
x.type = "password";
y.src = "png"
}
}
With the ! sign you said that this element won't be null (if you are sure that element is in your HTML document), and as HTMLInputElemnt is for indicating your element type.
To read more about it, you can read this article.
const x = document.getElementById("password-input")! as HTMLInputElement;
const y = document.getElementById("img")! as HTMLInputElement;
function showPass() {
if (x.type === "password") {
x.type = "text";
y.src = "png"
} else {
x.type = "password";
y.src = "png"
}
}
You can't just use TS in the browser, you'll need to compile it. For your specific use case, you will need to tell TS what the HTMLElement is for x and y, otherwise it won't like x.type and y.src as src and type aren't properties on HTMLElement
const x: HTMLInputElement = document.getElementById("password-input");
const y: HTMLImageElement = document.getElementById("img");
function showPass() {
if (x.type === "password") {
x.type = "text";
y.src = "png"
} else {
x.type = "password";
y.src = "png"
}
}