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
167 views
in Technique[技术] by (71.8m points)

reactjs - How to get interface key type in generic function?

I have a generic function that fetches some data:

function getData<T extends A | B | C>(initial: T[]): T[] {
  const [data, setData] = useState<T[]>([]);

  useEffect(() => {
    ...some query
    setData(query result);

  }, []);

  return data;
}

interface A {
  someKeyA: string;
}

interface B {
  someKeyB: number;
}

interface C {
  someKeyC: A;
}

In another helper function for query i need to get key types of T. If initial data array is not empty i can do this and it works

const _key = typeof data[0].["someKeyA" as keyof T];

But sometimes initial data array is empty and then this fails because data[0] is undefined.

What i would need is to get K extends keyof T if there is no passed in data. Is it possible to get typeof key from generic interface by key value or maybe create some temporary object with type T?

question from:https://stackoverflow.com/questions/65917619/how-to-get-interface-key-type-in-generic-function

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

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

2.1m questions

2.1m answers

60 comments

57.0k users

...