如何在不使用typescript中的选项(?)的情况下删除属性
我在删除属性时遇到问题。 例如:如何在不使用typescript中的选项(?)的情况下删除属性,typescript,Typescript,我在删除属性时遇到问题。 例如: type Person<GN> = { getName: GN extends never ? never : GN, } const foo = <GN>(person: Person<GN>) => person const first = foo({}) // should work const second = foo({ getName: (name: string) => n
type Person<GN> = {
getName: GN extends never ? never : GN,
}
const foo = <GN>(person: Person<GN>) => person
const first = foo({}) // should work
const second = foo({
getName: (name: string) => name,
})
type Person={
getName:GN从不扩展?从不:GN,
}
const foo=(person:person)=>person
const first=foo({})//应该可以工作
常数秒=foo({
getName:(name:string)=>name,
})
在本例中,first不需要getName属性。我怎样才能解决这个问题
使用可选的“?”属性将导致输出不清晰。 比如说
type Person<GN> = {
getName?: GN,
}
const foo = <GN>(person: Person<GN>) => person
const first = foo({}) // should work
first.getName // shouldn't exist 'getName' => but still have
const second = foo({
getName: (name: string) => name,
})
second.getName // should exist getName but in this case is optional property
type Person={
getName?:GN,
}
const foo=(person:person)=>person
const first=foo({})//应该可以工作
first.getName//不应存在“getName”=>但仍具有
常数秒=foo({
getName:(name:string)=>name,
})
second.getName//应该存在getName,但在本例中是可选属性
我怎样才能使输出清晰?
谢谢阅读。所以您希望将第一个
类型推断为{}
,第二个类型推断为{getName:(name:string)=>string;}
有一种方法可以做到这一点:
type Person<GN> = { getName: GN }
const foo = <GN, P extends Partial<Person<GN>>>(person: P) => person;
const first = foo({}) // const first: {}
const second = foo({ // const second: { getName: (name: string) => string; }
getName: (name: string) => name,
})
type Person={getName:GN}
const foo=(person:P)=>person;
const first=foo({})//const first:{}
const second=foo({//const second:{getName:(name:string)=>string;}
getName:(name:string)=>name,
})
那么您希望将第一个
类型推断为{}
,将第二个
类型推断为{getName:(name:string)=>string;}
有一种方法可以做到这一点:
type Person<GN> = { getName: GN }
const foo = <GN, P extends Partial<Person<GN>>>(person: P) => person;
const first = foo({}) // const first: {}
const second = foo({ // const second: { getName: (name: string) => string; }
getName: (name: string) => name,
})
type Person={getName:GN}
const foo=(person:P)=>person;
const first=foo({})//const first:{}
const second=foo({//const second:{getName:(name:string)=>string;}
getName:(name:string)=>name,
})