I am trying to use an interface that is declared few times with different key-value pairs and I want to restrict its keys to a template literal and values to a given generic type. This interface will be later used to define function input. I tried to check if key extends string, and it seemed to work but I was able to pass anything as a key, even number.
Here is the snippet of what I'd like to achieve:
// restrict interface keys and values
interface Test{
[k: string | number | symbol]: typeof k extends `${infer Prefix}#${infer Suffix}` ? { prefix: Prefix, suffix: Suffix } : never
}
interface Test{
'test1#test': { prefix: 'test1', suffix: 'test' }, // this throws, but shouldnt
}
interface Test{
'test2#test': { prefix: 'test2', suffix: 'test' }, // this throws, but shouldnt
}
There's unfortunately no way to constrain an interface the way you're trying to do here, at least not so that errors will appear directly on the lines you don't like. All my attempts ran afoul of circularity detectors, like
type CheckTest = { [K in keyof Test]:
K extends `${infer P}#${infer S}` ? { prefix: P, suffix: S } : never
};
interface Test extends CheckTest { } // error, circular!
Even if that didn't error, there's no implements clause for interfaces, so the constraint would be hard to represent directly. There's an open issue at microsoft/TypeScript#24274, and the workarounds listed in there are illegally circular, at least when I apply them here.
The closest I can think of is a line that checks whether Test is valid according to your rules, and which results in a compiler error at or near that line if there's a problem. This error will hopefully contain enough information for someone to find and fix the offending member of Test, although this is made less pleasant when you are using declaration merging and your members of Test are scattered throughout your code base.
Oh well, let's at least look at it:
type CheckTest = {
[K in keyof Test]: K extends `${infer P}#${infer S}` ?
{ prefix: P, suffix: S } : never
};
type VerifyTest<T extends Test = CheckTest> = T;
// ----------------------------> ^^^^^^^^^ <----- IS THERE AN ERROR HERE?
// if so, then some member of Test is bad.
// The error will tell you which one and what's wrong
The CheckTest type is similar to your definition except that it actually maps over the properties of Test instead of trying to use an index signature which treats the key as a single thing (typeof k is just string | number | symbol and not the specific keys of Test).
Anyway, CheckTest should be assignable to Test if Test is valid. Then the VerifyTest definition just assumes it's valid, by using CheckTest in a type position that needs to be assignable to Test.
Let's test it out. First we have this:
interface Test {
'test1#test': { prefix: 'test1', suffix: 'test' }
}
interface Test {
'test2#test': { prefix: 'test2', suffix: 'test' }
}
// ...
type VerifyTest<T extends Test = CheckTest> = T; // okay
No error, so we're good. Then someone comes along and does a bad thing:
interface Test {
'foo#bar': { prefix: "oof", suffix: "bar" }
}
And suddenly
type VerifyTest<T extends Test = CheckTest> = T; // error!
// ----------------------------> ~~~~~~~~~
/* The types of ''foo#bar'.prefix' are incompatible between these types.
Type '"foo"' is not assignable to type '"oof"' */
Which lets you know that it's time to find "foo"/"oof" in your code base and fix it.
Not pretty, but it's the closest I can get.
Playground link to code
Related
Existing JavaScript code has "records" where the id is numeric and the other attributes string.
Trying to define this type:
type T = {
id: number;
[key:string]: string
}
gives error 2411 id type number not assignable to string
There is no specific type in TypeScript that corresponds to your desired structure. String index signatures must apply to every property, even the manually declared ones like id. What you're looking for is something like a "rest index signature" or a "default property type", and there is an open suggestion in GitHub asking for this: microsoft/TypeScript#17867. A while ago there was some work done that would have enabled this, but it was shelved (see this comment for more info). So it's not clear when or if this will happen.
You could widen the type of the index signature property so it includes the hardcoded properties via a union, like
type WidenedT = {
id: number;
[key: string]: string | number
}
but then you'd have to test every dynamic property before you could treat it as a string:
function processWidenedT(t: WidenedT) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // error
if (typeof t.random === "string") t.random.toUpperCase(); // okay
}
The best way to proceed here would be if you could refactor your JavaScript so that it doesn't "mix" the string-valued bag of properties with a number-valued id. For example:
type RefactoredT = {
id: number;
props: { [k: string]: string };
}
Here id and props are completely separate and you don't have to do any complicated type logic to figure out whether your properties are number or string valued. But this would require a bunch of changes to your existing JavaScript and might not be feasible.
From here on out I'll assume you can't refactor your JavaScript. But notice how clean the above is compared to the messy stuff that's coming up:
One common workaround to the lack of rest index signatures is to use an intersection type to get around the constraint that index signatures must apply to every property:
type IntersectionT = {
id: number;
} & { [k: string]: string };
It sort of kind of works; when given a value of type IntersectionT, the compiler sees the id property as a number and any other property as a string:
function processT(t: IntersectionT) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // okay
t.id = 1; // okay
t.random = "hello"; // okay
}
But it's not really type safe, since you are technically claiming that id is both a number (according to the first intersection member) and a string (according to the second intersection member). And so you unfortunately can't assign an object literal to that type without the compiler complaining:
t = { id: 1, random: "hello" }; // error!
// Property 'id' is incompatible with index signature.
You have to work around that further by doing something like Object.assign():
const propBag: { [k: string]: string } = { random: "" };
t = Object.assign({ id: 1 }, propBag);
But this is annoying, since most users will never think to synthesize an object in such a roundabout way.
A different approach is to use a generic type to represent your type instead of a specific type. Think of writing a type checker that takes as input a candidate type, and returns something compatible if and only if that candidate type matches your desired structure:
type VerifyT<T> = { id: number } & { [K in keyof T]: K extends "id" ? unknown : string };
This will require a generic helper function so you can infer the generic T type, like this:
const asT = <T extends VerifyT<T>>(t: T) => t;
Now the compiler will allow you to use object literals and it will check them the way you expect:
asT({ id: 1, random: "hello" }); // okay
asT({ id: "hello" }); // error! string is not number
asT({ id: 1, random: 2 }); // error! number is not string
asT({ id: 1, random: "", thing: "", thang: "" }); // okay
It's a little harder to read a value of this type with unknown keys, though. The id property is fine, but other properties will not be known to exist, and you'll get an error:
function processT2<T extends VerifyT<T>>(t: T) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // error! random not known to be a property
}
Finally, you can use a hybrid approach that combines the best aspects of the intersection and generic types. Use the generic type to create values, and the intersection type to read them:
function processT3<T extends VerifyT<T>>(t: T): void;
function processT3(t: IntersectionT): void {
t.id.toFixed();
if ("random" in t)
t.random.toUpperCase(); // okay
}
processT3({ id: 1, random: "hello" });
The above is an overloaded function, where callers see the generic type, but the implementation sees the intersection type.
Playground link to code
You are getting this error since you have declared it as Indexable Type (ref: https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types) with string being the key type, so id being a number fails to conform to that declaration.
It is difficult to guess your intention here, but may be you wanted something like this:
class t {
id: number;
values = new Map<string, string>();
}
I had this same issue, but returned the id as a string.
export type Party = { [key: string]: string }
I preferred to have a flat type and parseInt(id) on the receiving code.
For my API, the simplest thing that could possibly work.
Existing JavaScript code has "records" where the id is numeric and the other attributes string.
Trying to define this type:
type T = {
id: number;
[key:string]: string
}
gives error 2411 id type number not assignable to string
There is no specific type in TypeScript that corresponds to your desired structure. String index signatures must apply to every property, even the manually declared ones like id. What you're looking for is something like a "rest index signature" or a "default property type", and there is an open suggestion in GitHub asking for this: microsoft/TypeScript#17867. A while ago there was some work done that would have enabled this, but it was shelved (see this comment for more info). So it's not clear when or if this will happen.
You could widen the type of the index signature property so it includes the hardcoded properties via a union, like
type WidenedT = {
id: number;
[key: string]: string | number
}
but then you'd have to test every dynamic property before you could treat it as a string:
function processWidenedT(t: WidenedT) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // error
if (typeof t.random === "string") t.random.toUpperCase(); // okay
}
The best way to proceed here would be if you could refactor your JavaScript so that it doesn't "mix" the string-valued bag of properties with a number-valued id. For example:
type RefactoredT = {
id: number;
props: { [k: string]: string };
}
Here id and props are completely separate and you don't have to do any complicated type logic to figure out whether your properties are number or string valued. But this would require a bunch of changes to your existing JavaScript and might not be feasible.
From here on out I'll assume you can't refactor your JavaScript. But notice how clean the above is compared to the messy stuff that's coming up:
One common workaround to the lack of rest index signatures is to use an intersection type to get around the constraint that index signatures must apply to every property:
type IntersectionT = {
id: number;
} & { [k: string]: string };
It sort of kind of works; when given a value of type IntersectionT, the compiler sees the id property as a number and any other property as a string:
function processT(t: IntersectionT) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // okay
t.id = 1; // okay
t.random = "hello"; // okay
}
But it's not really type safe, since you are technically claiming that id is both a number (according to the first intersection member) and a string (according to the second intersection member). And so you unfortunately can't assign an object literal to that type without the compiler complaining:
t = { id: 1, random: "hello" }; // error!
// Property 'id' is incompatible with index signature.
You have to work around that further by doing something like Object.assign():
const propBag: { [k: string]: string } = { random: "" };
t = Object.assign({ id: 1 }, propBag);
But this is annoying, since most users will never think to synthesize an object in such a roundabout way.
A different approach is to use a generic type to represent your type instead of a specific type. Think of writing a type checker that takes as input a candidate type, and returns something compatible if and only if that candidate type matches your desired structure:
type VerifyT<T> = { id: number } & { [K in keyof T]: K extends "id" ? unknown : string };
This will require a generic helper function so you can infer the generic T type, like this:
const asT = <T extends VerifyT<T>>(t: T) => t;
Now the compiler will allow you to use object literals and it will check them the way you expect:
asT({ id: 1, random: "hello" }); // okay
asT({ id: "hello" }); // error! string is not number
asT({ id: 1, random: 2 }); // error! number is not string
asT({ id: 1, random: "", thing: "", thang: "" }); // okay
It's a little harder to read a value of this type with unknown keys, though. The id property is fine, but other properties will not be known to exist, and you'll get an error:
function processT2<T extends VerifyT<T>>(t: T) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // error! random not known to be a property
}
Finally, you can use a hybrid approach that combines the best aspects of the intersection and generic types. Use the generic type to create values, and the intersection type to read them:
function processT3<T extends VerifyT<T>>(t: T): void;
function processT3(t: IntersectionT): void {
t.id.toFixed();
if ("random" in t)
t.random.toUpperCase(); // okay
}
processT3({ id: 1, random: "hello" });
The above is an overloaded function, where callers see the generic type, but the implementation sees the intersection type.
Playground link to code
You are getting this error since you have declared it as Indexable Type (ref: https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types) with string being the key type, so id being a number fails to conform to that declaration.
It is difficult to guess your intention here, but may be you wanted something like this:
class t {
id: number;
values = new Map<string, string>();
}
I had this same issue, but returned the id as a string.
export type Party = { [key: string]: string }
I preferred to have a flat type and parseInt(id) on the receiving code.
For my API, the simplest thing that could possibly work.
Existing JavaScript code has "records" where the id is numeric and the other attributes string.
Trying to define this type:
type T = {
id: number;
[key:string]: string
}
gives error 2411 id type number not assignable to string
There is no specific type in TypeScript that corresponds to your desired structure. String index signatures must apply to every property, even the manually declared ones like id. What you're looking for is something like a "rest index signature" or a "default property type", and there is an open suggestion in GitHub asking for this: microsoft/TypeScript#17867. A while ago there was some work done that would have enabled this, but it was shelved (see this comment for more info). So it's not clear when or if this will happen.
You could widen the type of the index signature property so it includes the hardcoded properties via a union, like
type WidenedT = {
id: number;
[key: string]: string | number
}
but then you'd have to test every dynamic property before you could treat it as a string:
function processWidenedT(t: WidenedT) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // error
if (typeof t.random === "string") t.random.toUpperCase(); // okay
}
The best way to proceed here would be if you could refactor your JavaScript so that it doesn't "mix" the string-valued bag of properties with a number-valued id. For example:
type RefactoredT = {
id: number;
props: { [k: string]: string };
}
Here id and props are completely separate and you don't have to do any complicated type logic to figure out whether your properties are number or string valued. But this would require a bunch of changes to your existing JavaScript and might not be feasible.
From here on out I'll assume you can't refactor your JavaScript. But notice how clean the above is compared to the messy stuff that's coming up:
One common workaround to the lack of rest index signatures is to use an intersection type to get around the constraint that index signatures must apply to every property:
type IntersectionT = {
id: number;
} & { [k: string]: string };
It sort of kind of works; when given a value of type IntersectionT, the compiler sees the id property as a number and any other property as a string:
function processT(t: IntersectionT) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // okay
t.id = 1; // okay
t.random = "hello"; // okay
}
But it's not really type safe, since you are technically claiming that id is both a number (according to the first intersection member) and a string (according to the second intersection member). And so you unfortunately can't assign an object literal to that type without the compiler complaining:
t = { id: 1, random: "hello" }; // error!
// Property 'id' is incompatible with index signature.
You have to work around that further by doing something like Object.assign():
const propBag: { [k: string]: string } = { random: "" };
t = Object.assign({ id: 1 }, propBag);
But this is annoying, since most users will never think to synthesize an object in such a roundabout way.
A different approach is to use a generic type to represent your type instead of a specific type. Think of writing a type checker that takes as input a candidate type, and returns something compatible if and only if that candidate type matches your desired structure:
type VerifyT<T> = { id: number } & { [K in keyof T]: K extends "id" ? unknown : string };
This will require a generic helper function so you can infer the generic T type, like this:
const asT = <T extends VerifyT<T>>(t: T) => t;
Now the compiler will allow you to use object literals and it will check them the way you expect:
asT({ id: 1, random: "hello" }); // okay
asT({ id: "hello" }); // error! string is not number
asT({ id: 1, random: 2 }); // error! number is not string
asT({ id: 1, random: "", thing: "", thang: "" }); // okay
It's a little harder to read a value of this type with unknown keys, though. The id property is fine, but other properties will not be known to exist, and you'll get an error:
function processT2<T extends VerifyT<T>>(t: T) {
t.id.toFixed(); // okay
t.random.toUpperCase(); // error! random not known to be a property
}
Finally, you can use a hybrid approach that combines the best aspects of the intersection and generic types. Use the generic type to create values, and the intersection type to read them:
function processT3<T extends VerifyT<T>>(t: T): void;
function processT3(t: IntersectionT): void {
t.id.toFixed();
if ("random" in t)
t.random.toUpperCase(); // okay
}
processT3({ id: 1, random: "hello" });
The above is an overloaded function, where callers see the generic type, but the implementation sees the intersection type.
Playground link to code
You are getting this error since you have declared it as Indexable Type (ref: https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types) with string being the key type, so id being a number fails to conform to that declaration.
It is difficult to guess your intention here, but may be you wanted something like this:
class t {
id: number;
values = new Map<string, string>();
}
I had this same issue, but returned the id as a string.
export type Party = { [key: string]: string }
I preferred to have a flat type and parseInt(id) on the receiving code.
For my API, the simplest thing that could possibly work.
I have a function that stores different values into the local storage by stringifying them and I want to limit the function from being able to work with Moment objects. The syntax would be this:
public static set<TValue>(
key: LocalStorageKeyEnum,
value: TValue,
...keySuffixes: string[]
) {
localStorage.setItem(
LocalStorage.buildKey(key, keySuffixes),
JSON.stringify(value)
)
}
The thing is the function would work without any issues if the second argument would be a Moment object and I want to exclude this type when writing <TValue>. Is there a way to do this using Typescript or the only way to go is running a check on run-time? I could work with 2 types, where the second would be a type that excludes the property of type Moment, like so
type Variants = {
value: TValue,
date: moment.Moment
}
type ExcludeDate = Exclude {typeof Variants, "date"}
but I was wondering if there's another way to do it. Thank you! I am new to Typescript so I am sorry if I wasn't very clear.
You can exclude type by conditional type:
type MomentType = { x: string } // just an example simulation of moment
function set<TValue>(
key: string,
value: TValue extends MomentType ? never : TValue, // pay attention here
...keySuffixes: string[]
) {
// implementation
}
set('key', { x: 'a' }) // error as its the MomentType
set('key', { y: 'a' }) // ok as its not the MomentType
The key line is value: TValue extends MomentType ? never : TValue. We say that if passed type extends our MomentType then the value is of the type never, what means you cannot pass value to it, as never is empty type (there is no instance of never).
MomentType was used only for example purposes, it can be any other type you want to exclude.
I'm trying to find a way to pass an object to function in and check it type in a runtime. This is a pseudo code:
function func (obj:any) {
if(typeof obj === "A") {
// do something
} else if(typeof obj === "B") {
//do something else
}
}
let a:A;
let b:B;
func(a);
But typeof always returns "object" and I could not find a way to get the real type of a or b. instanceof did not work either and returned the same.
Any idea how to do it in TypeScript?
Edit: I want to point out to people coming here from searches that this question is specifically dealing with non-class types, ie object
shapes as defined by interface or type alias. For class types you
can use JavaScript's instanceof to determine the class an instance comes from, and TypeScript will narrow the type in the type-checker automatically.
Types are stripped away at compile-time and do not exist at runtime, so you can't check the type at runtime.
What you can do is check that the shape of an object is what you expect, and TypeScript can assert the type at compile time using a user-defined type guard that returns true (annotated return type is a "type predicate" of the form arg is T) if the shape matches your expectation:
interface A {
foo: string;
}
interface B {
bar: number;
}
function isA(obj: any): obj is A {
return obj.foo !== undefined
}
function isB(obj: any): obj is B {
return obj.bar !== undefined
}
function func(obj: any) {
if (isA(obj)) {
// In this block 'obj' is narrowed to type 'A'
obj.foo;
}
else if (isB(obj)) {
// In this block 'obj' is narrowed to type 'B'
obj.bar;
}
}
Example in Playground
How deep you take the type-guard implementation is really up to you, it only needs to return true or false. For example, as Carl points out in his answer, the above example only checks that expected properties are defined (following the example in the docs), not that they are assigned the expected type. This can get tricky with nullable types and nested objects, it's up to you to determine how detailed to make the shape check.
Expanding on Aaron's answer, I've made a transformer that generates the type guard functions at compile time. This way you don't have to manually write them.
For example:
import { is } from 'typescript-is';
interface A {
foo: string;
}
interface B {
bar: number;
}
if (is<A>(obj)) {
// obj is narrowed to type A
}
if (is<B>(obj)) {
// obj is narrowed to type B
}
You can find the project here, with instructions to use it:
https://github.com/woutervh-/typescript-is
"I'm trying to find a way to pass an object to function in and check it type in a runtime".
Since a class instance is just an object, the "native" answer is to use a class instance and instanceof when runtime type checking is needed, use an interface when not in order to keep a contract and decouple your application, make reduce signature size on methods/ctors, while not add any additional size. In my humble opinion this is one of a few main considerations for me in TypeScript when deciding to use a class vs type/interface. One other main driving factor is whether the object will ever need to be instantiated vs if it for instance defines a POJO.
In my codebase, I will typically have a class which implements an interface and the interface is used during compilation for pre-compile time type safety, while classes are used to organize my code and allow for ease in passing data between functions, classes and method as well as do runtime type checks in typescript.
Works because routerEvent is an instance of NavigationStart class
if (routerEvent instanceof NavigationStart) {
this.loading = true;
}
if (routerEvent instanceof NavigationEnd ||
routerEvent instanceof NavigationCancel ||
routerEvent instanceof NavigationError) {
this.loading = false;
}
Will not work
// Must use a class not an interface
export interface IRouterEvent { ... }
// Fails
expect(IRouterEvent instanceof NavigationCancel).toBe(true);
Will not work
// Must use a class not a type
export type RouterEvent { ... }
// Fails
expect(IRouterEvent instanceof NavigationCancel).toBe(true);
As you can see by the code above, classes are used to compare the instance to the types NavigationStart|Cancel|Error within the Angular library and if you have used the router before you a project I am willing to be that you have done similar if not identical checks within your own codebase in order to determine application state during runtime.
Using instanceof on a Type or Interface is not possible, since the ts compiler strips away these attributes during its compilation process and prior to being interpreted by JIT or AOT. Classes are a great way to create a type which can be used pre-compilation as well as during the JS runtime.
Update 2022
In addition to my original response to this, you can leverage The TypeScript Reflect Metadata API or roll your own solution using the TypeScript compiler to do static analysis of your code and parse the AST, querying like so:
switch (node.kind) {
case ts.SyntaxKind.InterfaceDeclaration:
// ...
break;
case ts.SyntaxKind.TypeDeclaration:
// ...
break;
}
See this solution for additonal details
I've been playing around with the answer from Aaron and think it would be better to test for typeof instead of just undefined, like this:
interface A {
foo: string;
}
interface B {
bar: number;
}
function isA(obj: any): obj is A {
return typeof obj.foo === 'string'
}
function isB(obj: any): obj is B {
return typeof obj.bar === 'number'
}
function func(obj: any) {
if (isA(obj)) {
console.log("A.foo:", obj.foo);
}
else if (isB(obj)) {
console.log("B.bar:", obj.bar);
}
else {console.log("neither A nor B")}
}
const a: A = { foo: 567 }; // notice i am giving it a number, not a string
const b: B = { bar: 123 };
func(a); // neither A nor B
func(b); // B.bar: 123
No, You cannot reference a type in runtime, but yes you can convert an object to a type with typeof, and do validation/sanitisation/checks against this object in runtime.
const plainObject = {
someKey: "string",
someKey2: 1,
};
type TypeWithAllOptionalFields = Partial<typeof plainObject>; //do further utility typings as you please, Partial being one of examples.
function customChecks(userInput: any) {
// do whatever you want with the 'plainObject'
}
Above is equal as
type TypeWithAllOptionalFields = {
someKey?: string;
someKey2?: number;
};
const plainObject = {
someKey: "string",
someKey2: 1,
};
function customChecks(userInput: any) {
// ...
}
but without duplication of keynames in your code
You can call the constructor and get its name
let className = this.constructor.name
I know this is an old question and the "true" question here is not the
same as the question in the title, but Google throws this question for
"typescript runtime types" and some people may know what they are
looking for and it can be runtime types.
Right answer here is what Aaron Beall answered, the type guards.
But answer, matching question in the title and matching Google
searches, is only usage of TypeScript transformers/plugins. TypeScript
itself strip out information about types when transpiling TS to JS.
And well,.. it is one of the possible ways how to implement the type guards,
eg. the typescript-is transformer as user7132587 pointed out.
Another options is transformer tst-reflect. It provides all the information about types at runtime. It allows you to write own type guards based on type information, eg. checking that object has all the properties you expect. Or you can use directly Type.is(Type) method from the transformer, which is based directly on the TypeScript's type checking information.
I've created this REPL. Have a fun!
More info in Github repository.
import { getType, Type } from "tst-reflect";
class A {
alphaProperty: string;
}
interface B {
betaProperty: string;
}
class Bb extends A implements B {
betaProperty = "tst-reflect!!";
bBetaProperty: "yes" | "no" = "yes";
}
/** #reflectGeneric */
function func<TType>(obj?: TType)
{
const type: Type = getType<TType>();
console.log(
type.name,
"\n\textends", type.baseType.name,
"\n\timplements", type.getInterface()?.name ?? "nothing",
"\n\tproperties:", type.getProperties().map(p => p.name + ": " + p.type.name),
"\n"
);
console.log("\tis A:", type.is(getType<A>()) ? "yes" : "no");
console.log("\tis assignable to A:", type.isAssignableTo(getType<A>()) ? "yes" : "no");
console.log("\tis assignable to B:", type.isAssignableTo(getType<B>()) ? "yes" : "no");
}
let a: A = new A();
let b: B = new Bb();
let c = new Bb();
func(a);
func<typeof b>();
func<Bb>();
Output:
A
extends Object
implements nothing
properties: [ 'alphaProperty: string' ]
is A: yes
is assignable to A: yes
is assignable to B: no
B
extends Object
implements nothing
properties: [ 'betaProperty: string' ]
is A: no
is assignable to A: no
is assignable to B: yes
Bb
extends A
implements B
properties: [ 'betaProperty: string', 'bBetaProperty: ' ]
is A: no
is assignable to A: yes
is assignable to B: yes
You should use a separate dynamic typing library that allows you to define custom types with dynamic type information and track it's compliance to the expected type.
The best solution that allows you this is this amazing library: https://github.com/pelotom/runtypes
Using it, you can define a meta-type for your A and B types:
const AType = Record({foo: Number})
const BType = Record({baz: String})
This is pure TS, and you can note that we are creating constant objects, not static types. Also, we are using Number and String objects provided by the library, and not the TS static types of number and string.
Then, you create the static type declarations for A and B:
type A = Static<typeof AType>
type B = Static<typeof BType>
Now, these types are proper Typescript static types. They contain all the proper members that you passed during the creation of the meta-type, up to the infinite depth of objects. Arrays, objects, optionals, faulsy values, scalar types are all supported.
Then you can use this like this:
function asdf(object: any): A | undefined {
try {
const aObject = AType.check(object) // returns A if complies with Record definition, throws otherwise
return aObject
} catch {
return undefined
}
}
asdf({ foo: 3 }) // returns A, literally the same object since it passed the check
asdf({ bar: "3" }) // returns undefined, because no `foo` of type `number`
asdf({ foo: "3" }) // returns undefined, because `foo` has wrong type
This is the most modern, serious solution that works and scales beautifully.
You should use the "in" operator to narrow down. Reference
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
return animal.swim();
}
return animal.fly();
}
Alternative approach without the need of checking the type
What if you want to introduce more types? Would you then extend your if-statement? How many such if-statements do you have in your codebase?
Using types in conditions makes your code difficult to maintain. There's lots of theory behind that, but I'll save you the hazzle. Here's what you could do instead:
Use polymorphism
Like this:
abstract class BaseClass {
abstract theLogic();
}
class A extends BaseClass {
theLogic() {
// do something if class is A
}
}
class B extends BaseClass {
theLogic() {
// do something if class is B
}
}
Then you just have to invoke theLogic() from whichever class you want:
let a: A = new A();
a.theLogic();
let b: B = new B();
b.theLogic();