Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

javascript - Type backward referring in TypeScript

I need help with type declaration that contains a backward referring and I'll explain:

Given an interface Car like that:

interface Car {
  name: string,
  engine: Engine,
  brand: Brand,
  ...
}

I need to create a type of the following structure:

[ 'engine', (engine1, engine2) => {...} ]

Where engine1 and engine2 will be the same type as Car['engine'] and without limitation of generality - I need an array of:

[(keyof T) as S, (s1: S, s2: S) => { ... }]

In words: an array that contains exactly two elements: the first - is a property of T and the second is a function that accepts arg1 and arg2 where their type is the same type as the type of T[the first item in the array]

Can someone help me to declare such a type?

question from:https://stackoverflow.com/questions/65882713/type-backward-referring-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will do:

type MyType<T extends object> = { [S in keyof T]: [S, (s1: T[S], s2: T[S]) => any] }[keyof T];

const e: MyType<Car> = ['engine', (e1: Engine, e2: Engine) => { }];

Explanation (due to request in comment):

Just break it apart. Consider type:

type MyType1<T extends object, S extends keyof T> = [S, (s1: T[S], s2: T[S]) => any];

This type seems pretty obvious. But has one disadvantage - you must type key name explicitly.

const e: MyType1<Car, 'engine'> = ['engine', (e1: Engine, e2: Engine) => { }];

So you make union of all MyType1 possibilities for each property key:

type MyType2<T extends object> = { [S in keyof T]: MyType1<T, S> }[keyof T];

The original type above was just these two steps in one ;).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...