Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Type Exclusion?

Tags:

typescript

I know of type union & type intersection in type script but I couldn't find a syntax or workaround to use type exclusion. Is there a way to do that?

type ValidIndices = string ^ '_reservedProperty'; // All strings but '_reservedProperty'
interface MyInterface {
    [property: ValidIndices]: number;
    _reservedProperty: any;
}
like image 898
Serge Intern Avatar asked Nov 08 '22 21:11

Serge Intern


1 Answers

It's not a fully answer. But if you want to set exclusion for contsructor params you can use code like this:

declare type Params<T, K extends keyof T = never, D extends keyof T = never> = (
  {[P in K]: T[P]} &
  {[P in keyof T]?: T[P]} &
  {[P in D]?: undefined }
)
...
class Control{
  prop1: number
  prop2: number
  prop3: number
  prop4: number

  constructor(params: Params<Control, 'prop1' | 'prop2', 'prop4'>){
    Object.assign(this, params)
...

And you get:

params: {
  prop1: number
  prop2: number
  prop3?: number
  prop4?: undefined
}
like image 132
justerest Avatar answered Nov 15 '22 10:11

justerest