P
P
Pavlo Ponomarenko2019-04-09 12:08:49
typescript
Pavlo Ponomarenko, 2019-04-09 12:08:49

How to strengthen primitive type checking in TypeScript?

Let's admit at me primitive types are used in different places. In order not to complicate my life by creating classes, but at the same time, in order to be able to have static typing, I would like to specify the string type. Unfortunately, TypeScript doesn't check in any way that the type is valid. Tell me, is it possible to do what I aspire to and how?

type IFooIndex = string;
type IBarIndex = string;

class Foo {
    id: IFooIndex;
}

class Bar {
    id: IBarIndex;
}

function findFoo(index: IFooIndex) {
    // searching by IFooIndex
}

findFoo( new Bar().id ); // тут хотелось бы ошибку компиляции

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2019-04-09
@TheShock

Branding to help you

type IFooIndex = string & {_type?: 'foo'};
type IBarIndex = string & {_type?: 'bar'};

class Foo {
    id: IFooIndex;
}

class Bar {
    id: IBarIndex;
}

function findFoo(index: IFooIndex) {
    // searching by IFooIndex
}

findFoo( new Bar().id );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question