简体   繁体   中英

Interface property be of the type of a different interface property

So I am trying to coordinate two separate interfaces in an instance of a table, a table which I would like to make filtering optional so I started with two interfaces for this (leaving out the rest of the implementation). One to hold data about the columns and one to hold the data of the filtering

interface Column {
  headerTitle: string;
  headerId: string;
}

interface Filter {
  filteredHeaderIds: string []; // I would like this to be of type of headerId
  noDataMessage: string;
}

In the implementation above, I would want filterHeaderIds to be tied to whatever the user implements as a part of the Column .
Example:

const columns: Column[] = [{
  headerTitle: 'Person Name',
  headerId: 'name',
}, {
  headerTitle: 'Person Age',
  headerId: 'age',
}];

const filterData: Filter = {
  filteredHeaderIds: ['name','throwError'], 
  noDataMessage: 'No Data Found',
}

Since throwError isn't a defined headerId I would like to see if it's possible to have typescript throw an error. Is something like this possible?

Thanks!

The closest thing I can think of is string literal types . This would only be a valid solution if you are saying that your column definitions would be part of compiled code:

type ColumnHeaderId = 'name' | 'age';

interface Column {
  headerTitle: string;
  headerId: ColumnHeaderId;
}

interface Filter {
  filteredHeaderIds: ColumnHeaderId[];
  noDataMessage: string;
}

However, if you are wanting the columns to be completely dynamically generated, I think you'll be stuck with implementing run-time logical checking for ID fields matching.

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