Typescript: restrict to exact type by type name

Created on 15 Nov 2018  路  3Comments  路  Source: microsoft/TypeScript

The following will compile

interface Foo {
  success: boolean
}

interface Bar {
  success: boolean
}


const foo = (v: Foo) =>{

};

const bar = (v: Bar) =>{

};


bar(<Foo>{success: true});
bar(<Bar>{success: true});

it will compile because of the way that TS works, which is usually very convenient. But in some cases we may want to restrict to the exact type.

Basically, I am looking to prevent compilation for:

bar(<Foo>{success: true});

I want it to be restricted to:

bar(<Bar>{success: true}); 

is that possible?

Duplicate

Most helpful comment

What you want is #202
You should have a look at: https://michalzalecki.com/nominal-typing-in-typescript/#approach-2-brands
and an official answer: https://github.com/Microsoft/TypeScript/issues/25709#issuecomment-405449395

All 3 comments

What you want is #202
You should have a look at: https://michalzalecki.com/nominal-typing-in-typescript/#approach-2-brands
and an official answer: https://github.com/Microsoft/TypeScript/issues/25709#issuecomment-405449395

Aye, duplicate of #202.

This issue has been marked as a duplicate and has seen no activity in the last day. It has been closed for automatic house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kimamula picture kimamula  路  147Comments

yortus picture yortus  路  157Comments

rwyborn picture rwyborn  路  210Comments

quantuminformation picture quantuminformation  路  273Comments

rbuckton picture rbuckton  路  139Comments