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

typescript - How to create a function type which takes generic as parameter and has a return type dependent on the properties of the parameter

Sorry for the long and confusing title, but I'm not sure exactly how to describe whats necessary in a way that would facilitate a shorter one.

Basically what I want to do is create a type such as func<T>(filterProps:T): SomeReturnType where SomeReturnType is a new type created as a subtype of T but with only fields that are present in the supplied filterProps parameter.

For Example

interface User {
  name: String
  age: Number
  jobTitle: String
}

const user = find<User>({ name: true, age: true }) {
    // return Type should be inferred to { name: string, age: number }
}

user.name // no error
user.jobTitle // should display error
question from:https://stackoverflow.com/questions/65545675/how-to-create-a-function-type-which-takes-generic-as-parameter-and-has-a-return

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

1 Answer

0 votes
by (71.8m points)

Something like this?

function find<T, K extends keyof T>(thing: T, filterProps: K[]) {
  return thing as Pick<T, K>;
}

const ourUser: User = { name: 'John McClane', age: 44, jobTitle: 'Cop' };
const filteredUser = find(ourUser, ['name', 'age']); // Pick<User, "name" | "age">
filteredUser.name; // String
filteredUser.age; // Number
filteredUser.jobTitle; //error

Perhaps your version would "find" the thing from within the function body, rather than have it passed it as an argument.


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

...