Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

TypeScript 的类型问题

请教下,这里如何让 AccountResult2 继承 Account 的属性,同时 AccountResult2 还可以是 undefined

image.png


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

1 Answer

0 votes
by (71.8m points)

你想要的是不是这种效果?

// 合法
const t1: Account2 = undefined
// 合法
const t2: Account2 = { username: 'sdf', password: 2 }
// 合法
const t3: Account2 = { username: 'sdf', password: 2, hello: 'sdf' }
// 非法
const t4: Account2 = { hello: 'sdf' }
// 非法
const t5: Account2 = { username: 'sdf', hello: 'sdf' }

那可以这么写:

type Account2 = undefined | (Account & { [key: string]: any })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...