Variable 'test' is used before being assigned - Typescript
56,413
Solution 1
It is indeed unassigned. It is defined, but it has no value.
In my humble opinion, the cleanest way would be to return a literal:
const modifyData = (g: B):A => {
return {
name: g.name['ru'],
age: g.age,
sex: g.sex
} as A;
};
Solution 2
To clarify a little, this hinges on the difference between "assigned" and "defined." For example:
let myDate: Date; // I've defined my variable as of `Date` type, but it still has no value.
if (!someVariable) {
myDate = new Date();
}
console.log(`My date is ${myDate}`) // TS will throw an error, because, if the `if` statement doesn't run, `myDate` is defined, but not assigned (i.e., still has no actual value).
Defining simply means giving it an initial value:
let myDate: Date | undefined = undefined; // myDate is now equal to `undefined`, so whatever happens later, TS won't worry that it won't exist.
Solution 3
let test!: A;
add a '!' after variable name
Author by
dhruv2204
It's always good to start new things. :) I'm an optimistic learner.
Updated on July 09, 2022Comments
-
dhruv2204 almost 2 years
I am getting error in this implementation of typescript code. I am mapping here one type to another. But vscode shows error that variable 'test' is used before being assigned. can anyone please help?
interface A { name: string; age: string; sex: string; } interface B { name: any; age: string; sex: string; } const modifyData = (g : B) :A => { let test: A; test.name = g.name['ru']; test.age = g.age; test.sex = g.sex; return test as A; }; const g = [{ "name": { "en": "George", "ru": "Gregor" }, "age": "21", "sex": "Male" }, { "name": { "en": "David", "ru": "Diva" },, "age": "31", "sex": "Male" }]; const data = g.map(modifyData); console.log(data);
-
theisof about 3 yearsYes thanks, this was my issue. You don't need to explicitly assign undefined - TS just needs to know it is expected:
let myDate: Date | undefined;
-
Dmitry Koroliov over 2 yearsthe answer may be useful, but it's not at least for me. A brief explanation of what ! means here, would be very convenient
-
ogostos over 2 yearsThe main idea here is that Typescript calculates all possible scenarios, even the ones which are not so obvious at first glance, thus its inference ability encounters a possible
null
orundefined
type. So if you are certain that certain variable actually will not benull
orundefined
, you may hint TS by postfix!
, which simply removesnull
andundefined
from the type of an expression. More info -
Ross Coundon over 2 yearsAnother way to put it is the ! operator means you want to tell the compiler that you know best. You are asserting that the value will always be specified. It's rare that you should need to do this as it's easy to get caught out at runtime.
-
cprcrack about 2 yearsIt's called Definite Assignment Assertions: typescriptlang.org/docs/handbook/release-notes/…