Typescript type compatibility test

Does Typescript support a direct structural type compatibility test?

C # supports operator isand creates surfaceIsAssignableFrom(object instance)

if (foo is SomeType) ...
if (SomeType.IsAssignableFrom(foo)) ...

Is there any direct way to do this kind of validation in Typescript or do I need to try for each of the required members?

instanceofwill probably do this for the case in question, but does not comply with structural compatibility, instead checks the prototype chain.

Yes, I know, Typescript is instanceofdirectly equivalent to the C # operator is. But I started by pointing out structural typing.

Maybe I should put the quack method on Object

+4
source share
1 answer

,

, !

, , Typescript . . , , , , .

, (), .


Typescript 1.6,

// ( ). , , (.hasOwnProperty ..), . .

function isConfigGetMsg(msg: BaseMessage): msg is ConfigGetMsg {
  return msg.name === MsgTypes.CONFIG_GET_MSG;
}

//and use it as
if (isConfigGetMsg(msg)){
    console.log(msg.key); //key being a ConfigGetMsg only value
}

, . , , . , .


, . , , - :

interface One {
    a: number
}
interface Two extends One {
    b: string
}
function isAssignableTo<T>(potentialObj:Object, target:T) : potentialObj is T {
    return Object.keys(target).every(key => potentialObj.hasOwnProperty(key))
}

let a: Object = {
    a: 4,
    b: 'hello'
};

let b: Two = undefined;

if(isAssignableTo(a, b)) {
    b = a;
}

isAssignableTo. , , , , , . . , - , , , . , .


, , "" - , . , , , /. , , typescript ., tsconfig.

, api. , . isAssignableTo . , , , , .


, , . , . , ;).

+1

All Articles