简体   繁体   中英

how to declare a variable with two types via typescript

I want to declare a variable with two types via ts.But the complier tips error. like this:

 interface IAnyPropObject { [name: string]: any; } let a: IAnyPropObject | ((str: string) => any); aB = "bbbbbbbb";//tips error a("");//tips error 

note:I don't want to use 'any' to declare.I just want to constraint the variable by this way only.Because of the code are so old and they are not TS code.

If you use an OR type, that doesn't mean your object has two types at the same time, you have to test it and use the correct type with casting inside of the test.

See https://www.typescriptlang.org/docs/handbook/advanced-types.html

interface IAnyPropObject { [name: string]: any; }
type MyFunc = (str: string) => any;
let a: IAnyPropObject | ((str: string) => any);
if (a instanceof Function) {
     (<MyFunc>a)("hi"); //passing a number will throw an error
} else {
    (<IAnyPropObject>a).b = 'bbbbbbbb';
}

You could also create a custom type guard, it's explained in the documentation I linked to, then you would not have to cast it. There's a lot more to be said, I just scratched the surface since I'm answering from my phone, read the doc for all the details.

Brief explanation of Mixin vs Union types.

Union: Either this or that type, but not both.

interface A { [name: string]: any; }
interface B { (str: string): string; }
type UnionType = A | B;

Mixin: A mix of this and that type at the same time.

interface A { [name: string]: any; }
interface B { (str: string): string; }
type MixinType = A & B;

Your code would work if you use a Mixin type, if that is your intention. Variable a can have a mix of both types at the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM