in the example below, i want to assign a variable like i do to x1
and have it be type C
. i can accomplish this with the way i do x2
or presumably with as
but that's clunky or unsafe. is there a nice way to do this? i'd like type C
so that some type inference stuff later down the line works right.
type A = {foo: "foo"}
type B = {bar: "bar"}
type C = A | B
let x1: C = {foo: "foo"}
console.log(x1) // <- x1 is type A (what i want is for it to be C)
let x2: C = ((): C => ({foo: "foo"}))()
console.log(x2) // <- x2 is type C (desired)
CodePudding user response:
This looks like it may be a case for a type assertion using as
:
let x1: C = {foo: 'foo'} as C;
Though I'm not sure what use case might require TypeScript to not know what specific type of C
value you've assigned to x1
?
With the way you have it currently, TypeScript does know that x1
is of type C
. You can see this by trying to assign it a value of type B
later, for example, and it will still work, though in that case TypeScript will still know you've given it a value of type B
.
let x1: C = {foo: "foo", bar: 'bar'};
console.log(x1) // <- x1 is type A (what i want is for it to be C)
x1 = {bar: 'bar'};
console.log(x1) // <- TypeScript knows x1 now holds a value of type B
You can also see that if you assign it a type that matches A & B
then TypeScript will not try to narrow its type any further than C
:
let x1: C = {foo: 'foo', bar: 'bar'};