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

ts 类型提取问题

如何修改第三行返回的类型,使 result 拥有 age: number
同时现有的返回的类型也还要在

image.png


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

1 Answer

0 votes
by (71.8m points)

试试这个是否符合你的需求

// 必须这样写,不能让ts自行推断
let rename: {
    type: 'product_type',
    teacher_name: 'name',
} = {
    type: 'product_type',
    teacher_name: 'name',
};
// 如果使用typescript>=3.4,可以使用const断言,更加简洁
let rename = {
    type: 'product_type',
    teacher_name: 'name',
} as const;


function reobjectKeys<V, T extends { [key: string]: keyof V }>(obj: V, rule: T): Omit<V, T[keyof T]> & { [K in keyof T]: V[T[K]] } {
    // ..
}

const result = reobjectKeys(query, rename);

// 以下应该能正常提示key和type
result.age;
result.type;
result.teacher_name;

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

...