简体   繁体   中英

How can I extract the properties of an interface using TypeScript (preferably with no 3rd party libs)

I need to get the properties of an interface to make sure that they match an object that implements it. For unit testing purposes.

So if changes are made to the interface the unit test should break if it isn't updated with the new members.

I've tried using the ts-transformer-keys package but it throws an error about not being a function.

   interface Test {
      mem1: boolean,
      mem2: string
   }

I would like to do something like this:

   console.log(Object.keys(Test))

and expect

   ['mem1', 'mem2'];

Interfaces don't exist at runtime, so extracting any information from an interface at run-time is not possible. You can create an object that has all the keys of the interface. The compiler will force you to specify all keys and will check that no extra keys are present so the duplication will never be out of sync with the interface:

interface Test {
    mem1: boolean,
    mem2?: string
}


function interfaceKeys<T>(keys: Record<keyof T, 1>) {
    return Object.keys(keys) as Array<keyof T>
}

console.log(interfaceKeys<Test>({
    mem1: 1,
    mem2: 1
}))

console.log(interfaceKeys<Test>({ // error
    mem1: 1,
}))

console.log(interfaceKeys<Test>({
    mem1: 1,
    mem2: 1,
    mem3: 1,     // error 
}))

play

您可以使用type SomeType = ClientType['birthdate']提取它

If you are okay with having it added during a compile time and you are using TypeScript >= 2.4.1, you can try the way proposed here .

Basically, you should add the ts-transformer-keys dependency , custom transformer , like a basic one and you'll be able to list the properties like this:

import { keys } from 'ts-transformer-keys';

interface Props {
    id: string;
    name: string;
    age: number;
}

const keysOfProps = keys<Props>();

console.log(keysOfProps); // ['id', 'name', 'age']

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